Pet*_*ock 3 arrays split sql-server-2005
我在数据库表中有字符串,如下所示:
Peter/Parker/Spiderman/Marvel
Bruce/Wayne/Batman/DC
Run Code Online (Sandbox Code Playgroud)
SQL中是否有一种方法可以从字符串中提取特定值,例如
Name = MyColumn(0)
SurName = MyColumn(1)
Character = MyColumn(3)
Company = MyColumn(4)
Run Code Online (Sandbox Code Playgroud)
谢谢
Bri*_*dge 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
Run Code Online (Sandbox Code Playgroud)
如果有可变数量的部件,你需要找到一个字符串拆分功能来为你做这个,没有一个好的内置.很多选项可以找到搜索SO:https://stackoverflow.com /搜索q = [SQL服务器+] +串+裂
警告字 - 如果您尝试使用PARSENAME1-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;
Run Code Online (Sandbox Code Playgroud)
结果是:
| NAME | SURNAME | CHARACTER | COMPANY |
-----------------------------------------
| Peter | Parker | Spiderman | Marvel |
| Bruce | Wayne | Batman | DC |
Run Code Online (Sandbox Code Playgroud)
或者您可以实现拆分数据的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
Run Code Online (Sandbox Code Playgroud)