SQL Server 2005中:字符串分割到数组,并得到阵列(X)?(SQL Server 200

2019-08-03 08:49发布

我有这样一个数据库表中的字符串:

Peter/Parker/Spiderman/Marvel
Bruce/Wayne/Batman/DC

有没有在SQL的方式从字符串如提取特定的值

Name = MyColumn(0)
SurName = MyColumn(1)
Character = MyColumn(3)
Company = MyColumn(4)

谢谢

Answer 1:

如果你知道你将会有确切的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;

请参阅SQL拨弄演示

其结果是:

|  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

请参阅SQL拨弄演示



Answer 2:

我在这里假设有总是精确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搜索: https://stackoverflow.com /搜索q = [SQL服务器+] +串+裂

提醒一句-如果你尝试使用了一些与PARSENAME比1-4等,结果将始终为NULL。



文章来源: SQL Server 2005 : split string into array and get array(x)?