关于如何在不使用自定义函数的情况下从较大的字符串中提取子字符串,我遇到了困境 字符串是这种形式:
" [1].[2]"
" [1].[2].[3]"
" [1].[2].[3].[4]"
基本上,它是一个层次结构,对于节点的每个子节点都有4个前导空格。任务是为每个节点维护这4个前导空格,但最后只获得孩子,没有完整路径
所以,最终的结果应该是这样的:
" [2]"
" [3]"
" [4]"
有人可以帮助我吗?
编辑:或者,如果是这样的话,我应该修改构建结果集的CTE吗?
CTE如下所示:
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)
谢谢!
答案 0 :(得分:1)
尝试这样的事情
DECLARE @mockup TABLE(YourString VARCHAR(100));
INSERT INTO @mockup VALUES
(' [1]')
,(' [1].[2]')
,(' [1].[2].[3]')
,(' [1].[2].[3].[4]');
SELECT LEFT(YourString,CHARINDEX('[',YourString)-1)
+SUBSTRING(YourString,LEN(YourString)+1-CHARINDEX('[',REVERSE(YourString)),1000)
FROM @mockup;
答案 1 :(得分:0)
我会将空格部分与最后一个索引连接起来。 像
这样的东西Select left(your_string, char_index(your_string, "[") - 1) +
right(your_string, 3) from your_table
3假设总是有一位数。如果没有,这有点复杂,因为SQLServer中没有最后一个索引:
Select left(your_string, char_index(your_string, "[") - 1) +
reverse(left(reverse(your_string), char_index(reverse(your_string), "[")))
from your_table