提取 SQL 中两个字符之间但有多个相同字符的字符串部分
Extract part of string in SQL that is between two character but there are multiple of same characters
我正在尝试提取两个字符之间的字符串部分,该字符串看起来像 -
EXAMPLE/EXMPL/BBASIC/示例/示例
我要移至单独列的文本是第 4 个文本部分,介于第 3 个和第 4 个“/”(粗体)之间
在不了解DBMS的情况下,我不确定是否有内置的拆分功能。 SQL Server 2008 R2没有拆分功能,所以我是这样处理的:
declare @str varchar(max) = 'example/example/bbasic/eXaMpLe/example', @delim char(1) = '/'
;with vars(id, _start, _end) as
(
select 1, cast(1 as bigint), charindex(@delim, @str)
union all
select id + 1, _end + 1, charindex(@delim, @str, _end + 1)
from vars
where _end > 0
)
select id, cast(substring(@str, _start, case when _end > 0 then _end - _start else len(@str) - _start + 1 end) as varchar(max)) as value
from vars
where id = 4
option (MAXRECURSION 0)
使用where id = 4
表示在第3 个/
分隔符之后拉出第4 个元素。这个SQLreturns:
id value
--- --------
4 eXaMpLe
我正在尝试提取两个字符之间的字符串部分,该字符串看起来像 -
EXAMPLE/EXMPL/BBASIC/示例/示例
我要移至单独列的文本是第 4 个文本部分,介于第 3 个和第 4 个“/”(粗体)之间
在不了解DBMS的情况下,我不确定是否有内置的拆分功能。 SQL Server 2008 R2没有拆分功能,所以我是这样处理的:
declare @str varchar(max) = 'example/example/bbasic/eXaMpLe/example', @delim char(1) = '/'
;with vars(id, _start, _end) as
(
select 1, cast(1 as bigint), charindex(@delim, @str)
union all
select id + 1, _end + 1, charindex(@delim, @str, _end + 1)
from vars
where _end > 0
)
select id, cast(substring(@str, _start, case when _end > 0 then _end - _start else len(@str) - _start + 1 end) as varchar(max)) as value
from vars
where id = 4
option (MAXRECURSION 0)
使用where id = 4
表示在第3 个/
分隔符之后拉出第4 个元素。这个SQLreturns:
id value
--- --------
4 eXaMpLe