我有一张像
这样的表select SupplierID,ProductIDs from T_ProductSupplierTable
输出
SupplierID ProductIDs
1 1,2,3
2 2,3,4
3 1,5,2
我需要像
这样的答案SupplierID ProductIDs
1 1
1 2
1 3
2 2
2 3
2 4
3 1
3 5
3 2
如何生成查询......?
答案 0 :(得分:0)
您可以使用一些准备在Internet上使用的功能来拆分字符串并转换为表格,以后您可以加入SubpplierID。
不使用功能的另一个选项是Sample in SQL Fiddle
SELECT supplierid,
LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS ProductIDs
FROM
(
SELECT supplierid,CAST('<XMLRoot><RowData>' + REPLACE(ProductIDs ,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
FROM tab
)t
CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)
答案 1 :(得分:0)
此外,你可以使用递归cte。 Sample
with cte as (
select SupplierID, ProductIDs as IDs, cast(null as varchar(8000)) as Product, charindex(',',ProductIDs) as nxt
from tab
union all
select SupplierID, substring(IDs,nxt+1,8000), left(IDs,nxt-1), charindex(',',IDs,nxt+1)-nxt
from cte where nxt > 0
union all
select SupplierID, null, IDs, null
from cte where nxt <= 0
)
select supplierid, Product from cte where Product is not null