我有一个包含以下列的表
Name
----------------------
test10/20000020
test1/test2 / 20000001
test3/test4 / 20000002
test5/20000017
test5/test6 / 20000004
test5/20000007
我需要选择最后一个值 即
20000020
20000001
20000002
20000017
20000004
20000007
我试过
(SUBSTRING(Name,0,(CHARINDEX('/',Name,0))))
但我获得了第一价值 即test1 TEST2 TEST3
答案 0 :(得分:1)
使用XML:
declare @xml xml;
declare @str nvarchar(max) = '';
with data as
(
select 'test1/test2/test3/344495' as r
union ALL
select 'test1/344556' as r
)
select @str = @str + '<r><v>' + replace(r,'/','</v><v>') + '</v></r>'
from data;
-- obtain xml
set @xml = cast(@str as xml);
-- select last value from each row
select v.value('(v/text())[last()]', 'nvarchar(50)')
from @xml.nodes('/r') as r(v)
相同的想法,但没有变量:
;with data as
(
select 'test1/test2/test3/344495' as r
union ALL
select 'test1/344556' as r
),
xmlRows AS
(
select cast('<r><v>' + replace(r,'/','</v><v>') + '</v></r>' as xml) as r
from data
)
select v.value('(v/text())[last()]', 'nvarchar(50)') as lastValue
from xmlRows xr
cross APPLY
r.nodes('/r') as r(v)
答案 1 :(得分:1)
SELECT SUBSTRING(Name,LEN(Name) - CHARINDEX('/',REVERSE(Name))+ 2,LEN(Name))FROM SAMPLE
为我工作
答案 2 :(得分:0)
SUBSTRING(表达式,开始,长度)
而不是那个
(SUBSTRING(Name,0,(CHARINDEX('/',Name,0))))
你应该使用
(SUBSTRING(Name,(CHARINDEX('/',Name,0)+1),8))
如果字符串大小是固定的。
答案 3 :(得分:0)
您可以使用以下查询解决问题:
SELECT (SUBSTRING(Name,(CHARINDEX('/',Name,0)),LEN(Name)))