I have a dilemma regarding how to extract a sub string from a larger string without using custom functions The string is of this form:
" [1].[2]"
" [1].[2].[3]"
" [1].[2].[3].[4]"
Basically, it's a hierarchy that has 4 leading spaces for every child of a node. The task is to maintain those 4 leading spaces for every node, but get only the child in the end, without the full path
So, the final result should be something like this:
" [2]"
" [3]"
" [4]"
Could anyone help me?
Edit: or, if it's the case, should I modify the CTE that is building the result set?
The CTE is like the one below:
WITH Hierarchy(cid, cname, parent_id, Parents, nname)
AS
(
SELECT map_id, name, parent_id, CAST('' AS VARCHAR(MAX)), CAST(''+name AS VARCHAR(MAX))
FROM tblMapping AS tm1
WHERE parent_id = 0
UNION ALL
SELECT tm.map_id, tm.name, Parent.cid,
CAST(CASE WHEN Parent.Parents = ''
THEN(CAST(tm.parent_id AS VARCHAR(MAX)))
ELSE(Parent.Parents + '.' + CAST(tm.parent_id AS VARCHAR(MAX)))
END AS VARCHAR(MAX)),
-- add the formated column description
CAST(CASE WHEN Parent.Parents = ''
THEN(Parent.cname)
ELSE(' '+Parent.nname+ '.'+tm.name)
END AS VARCHAR(MAX))
FROM tblMapping AS tm
INNER JOIN Hierarchy AS Parent ON tm.parent_id = Parent.cid
)
SELECT *
FROM Hierarchy
ORDER BY ltrim(nname)
OPTION(MAXRECURSION 32767)
Thank you!