如果我有这样的值
Name varchar(255) = 'A fox Jumped/ in to the water/ and fought with crocodile/ and then went back/ to jungle and slept'
我想使用'/'作为分隔符来提取值。我可以弄清楚如何将这部分 '提取到丛林并睡觉' ,但是我想获得倒数第二个值 '然后去返回' 以及'/' ”之后的整个部分,然后返回丛林并睡觉”
Expected values:
1. 'and then went back'
2. 'and then went back/ to jungle and slept'
答案 0 :(得分:0)
这可以通过将reverse
,substring
和charindex
与cross apply
结合使用来完成。使用一系列cross apply
找出字符的第一个,第二个(和第n个出现),然后提取所需的子字符串。
select
reverse(substring(reverse(str), p1.pos+1, p2.pos-p1.pos-1)) as between_first_sec_from_last
,reverse(substring(reverse(str), 1, p2.pos- 1)) as upto_second_from_last
from (select 'A fox Jumped/ in to the water/ and fought with crocodile/ and then went back/ to jungle and slept' as str) t
cross apply (select (charindex('/', reverse(str)))) as p1(pos)
cross apply (select (charindex('/', reverse(str), p1.pos+1))) as p2(pos)