我在这样的数据库表中有字符串:
Peter/Parker/Spiderman/Marvel
Bruce/Wayne/Batman/DC
SQL中有没有办法从字符串中提取特定值,例如
Name = MyColumn(0)
SurName = MyColumn(1)
Character = MyColumn(3)
Company = MyColumn(4)
谢谢
我在这样的数据库表中有字符串:
Peter/Parker/Spiderman/Marvel
Bruce/Wayne/Batman/DC
SQL中有没有办法从字符串中提取特定值,例如
Name = MyColumn(0)
SurName = MyColumn(1)
Character = MyColumn(3)
Company = MyColumn(4)
谢谢
我在这里假设总是正好有 4 个部分。
如果是这样,您可以替换/
并.
使用内置的ParseName函数。您的示例中唯一的问题是它从最后开始计算,因此您需要注意您想要的部分:
DECLARE @test VARCHAR(max);
SET @test = 'Peter/Parker/Spiderman/Marvel';
SET @test = Replace(@test, '/', '.');
SELECT Parsename(@test, 4),--returns Peter
Parsename(@test, 3),--returns Parker
Parsename(@test, 2),--returns Spiderman
Parsename(@test, 1) --returns Marvel
如果有可变数量的部分,您需要找到一个字符串拆分功能来为您执行此操作,没有一个好的内置功能。可以通过搜索找到许多选项:https ://stackoverflow.com /search?q=[sql+server]+string+split
警告 - 如果您尝试使用PARSENAME
1-4 以外的数字,结果将始终为 NULL。
如果你知道你将有 4 列,那么你也可以使用这个嵌套的 CTE 版本:
;with s1 (name, extra) as
(
select left(data, charindex('/', data)-1),
substring(data, charindex('/', data) +1, len(data))
from yourtable
),
s2 (name, surname, extra) as
(
select name,
left(extra, charindex('/', extra)-1),
substring(extra, charindex('/', extra)+1, len(extra))
from s1
),
s3 (name, surname, [character], company) as
(
select name,
surname,
left(extra, charindex('/', extra)-1),
substring(extra, charindex('/', extra)+1, len(extra))
from s2
)
select *
from s3;
结果是:
| NAME | SURNAME | CHARACTER | COMPANY |
-----------------------------------------
| Peter | Parker | Spiderman | Marvel |
| Bruce | Wayne | Batman | DC |
或者,您可以同时实现拆分数据的 CTE,然后实现PIVOT
:
;with cte (item, data, colNum, rn) as
(
select cast(left(data, charindex('/',data+'/')-1) as varchar(50)) item,
stuff(data, 1, charindex('/',data+'/'), '') data,
1 colNum,
row_number() over(order by data) rn
from yourtable
union all
select cast(left(data, charindex('/',data+'/')-1) as varchar(50)) ,
stuff(data, 1, charindex('/',data+'/'), '') data,
colNum+1,
rn
from cte
where data > ''
)
select [1] as Name,
[2] as Surname,
[3] as [character],
[4] as company
from
(
select item, colnum, rn
from cte
) src
pivot
(
max(item)
for colnum in ([1], [2], [3], [4])
) piv