我在数据库表中有这样的字符串:
Peter/Parker/Spiderman/Marvel
Bruce/Wayne/Batman/DC
SQL中是否有一种方法可以从字符串中提取特定值,例如
Name = MyColumn(0)
SurName = MyColumn(1)
Character = MyColumn(3)
Company = MyColumn(4)
由于
答案 0 :(得分:13)
我在这里假设总有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
如果有可变数量的部件,你需要找到一个字符串拆分功能来为你做这个,内置的不是很好。搜索SO时可以找到很多选项:{{3} }
警告提示 - 如果您尝试使用除{1}以外的PARSENAME
的数字,则结果将始终为NULL。
答案 1 :(得分:5)
如果您知道您将有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