我需要将逗号分隔的列拆分为行而不影响其他列。
我的桌子......
+-----+--------------+------------+-------------+
| id | parent_title | account_id | tags |
+-----+--------------+------------+-------------+
| 647 | title999 | 64 | 361,381,388 |
| 646 | title998 | 64 | 361,376,388 |
+-----+--------------+------------+-------------+
预期表......
+-----+--------------+------------+------+
| id | parent_title | account_id | tags |
+-----+--------------+------------+------+
| 647 | title999 | 64 | 361 |
| 647 | title999 | 64 | 381 |
| 647 | title999 | 64 | 388 |
| 646 | title998 | 64 | 361 |
| 646 | title998 | 64 | 376 |
| 646 | title998 | 64 | 388 |
+-----+--------------+------------+------+
答案 0 :(得分:1)
获得良好的字符串拆分功能。没有数据库应该没有数据库。
http://www.sqlservercentral.com/articles/Tally+Table/72993/
然后,执行此操作(注意这假设您已经构建了一个字符串拆分函数,它被称为SplitStrings_CLR())
;with t as
(
select id = 647, parent_title = 'title999', account_id = 64, tags = '361,381,388' union all
select id = 646, parent_title = 'title998', account_id = 64, tags = '361,381,388'
)
select
id,
parent_title,
account_id,
x.*
from t
cross apply sysmon.dbo.SplitStrings_CLR(tags, ',') x
答案 1 :(得分:0)
使用XML
技巧来执行此操作。
SELECT id,
parent_title,
account_id,
Split.a.value('.', 'Int') tags
FROM (SELECT id,
parent_title,
account_id,
Cast ('<M>' + Replace(tags, ',', '</M><M>') + '</M>' AS XML) AS Data
FROM [table]) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)