我有一些代码,它在典型字符串中选择第一个和第二个'/'之间的字符串,如下所示:
2014-天花板/天花板/修复/石棉/ Supalux
以下代码正确返回上例中的“Ceilings”值。
SELECT
REPLACE (LEFT(SUBSTRING(ElementPath,CHARINDEX
('/',ElementPath)+1,LEN(ElementPath)),CHARINDEX
('/',SUBSTRING(ElementPath, CHARINDEX
('/',ElementPath)+1,LEN(ElementPath)))),'/','')
FROM K2_Master.dbo.tbElement
如何修改它以选择第二个和第三个'/'之间的字符串以返回值'Repair'?
由于
答案 0 :(得分:2)
检查这个小技巧可能有效:
DECLARE @String VARCHAR(100)= '2014-Ceilings/Ceilings/Repair/Asbestos/Supalux'
SET @String = '<N>' + Replace(@String, '/', '</N><N>')
+ '</N>'
SELECT c.value('/N[1]', 'varchar(30)'),
c.value('/N[2]', 'varchar(30)'),
c.value('/N[3]', 'varchar(30)')
FROM (SELECT Cast(@String AS XML)) t(c)
SELECT c1.value('.', 'varchar(30)')
FROM (SELECT CAST(@String AS XML)) t(c)
CROSS APPLY c.nodes('/N') AS t1(c1)
SELECT value
FROM (SELECT c1.value('.', 'varchar(30)') AS value,
ROW_NUMBER()
OVER(
ORDER BY (SELECT 1)) rn
FROM (SELECT Cast(@String AS XML)) t(c)
CROSS APPLY c.nodes('/N') AS t1(c1)) temp
WHERE rn = 3
在你的情况下
SELECT c.value('/N[1]', 'varchar(30)'),
c.value('/N[2]', 'varchar(30)'),
c.value('/N[3]', 'varchar(30)')
FROM (SELECT Cast ('<N>' + Replace( Replace (ElementPath, '/', '</N><N>'),'&','&')
+ '</N>' AS XML)
FROM K2_Master.dbo.tbElement) t(c)
答案 1 :(得分:1)
我追了你的问题,结果很长......
DECLARE @a VARCHAR(40) = '2014-Ceilings/Ceilings/Repair/Asbestos/Supalux'
SELECT @a
,LEFT(
SUBSTRING(SUBSTRING(@a,CHARINDEX('/',@a,1)+1,LEN(@a)),CHARINDEX('/',SUBSTRING(@a,CHARINDEX('/',@a,1)+1,LEN(@a)),1)+1,LEN(SUBSTRING(@a,CHARINDEX('/',@a,1)+1,LEN(@a)))),
CHARINDEX('/',SUBSTRING(SUBSTRING(@a,CHARINDEX('/',@a,1)+1,LEN(@a)),CHARINDEX('/',SUBSTRING(@a,CHARINDEX('/',@a,1)+1,LEN(@a)),1)+1,LEN(SUBSTRING(@a,CHARINDEX('/',@a,1)+1,LEN(@a)))),1) - 1
)
结果:
回答你的评论。
DECLARE @String VARCHAR(100)= '2014-Ceilings/Ceilings/Repair/Asbestos/Supalux',
@value INT = 2
DECLARE @itra INT = 1
WHILE @itra <= @value
BEGIN
SET @String = (SELECT SUBSTRING(@String,CHARINDEX('/',@String,1)+1,LEN(@String)))
--SELECT @String
SET @itra = @itra + 1
END
SELECT LEFT(@String, CHARINDEX('/',@String,1) - 1)
将“/”的位置设为@value
并查看结果。对于上面的sql,结果是Repair
。如果您提供@value = 3,
结果为Asbestos