以北風資料庫為例
【單個資料表】
Select top 5 CustomerID
From dbo.Customers
For Xml Path('')
結果:<CustomerID>ALFKI</CustomerID><CustomerID>ANATR</CustomerID><CustomerID>ANTON</CustomerID><CustomerID>AROUT</CustomerID><CustomerID>BERGS</CustomerID>
(使用逗號分隔)
Select top 5 ','+ CustomerID
From dbo.Customers
For Xml Path('')
結果:,ALFKI,ANATR,ANTON,AROUT,BERGS
(使用SUBSTRING去除開頭的逗號)
-- SUBSTRING(原字串, 起始位置, 取得長度):起始位置為1
Select SUBSTRING(
(Select top 5 ',' + CustomerID
From dbo.Customers
For Xml Path(''))
, 2, 8000)
結果:ALFKI,ANATR,ANTON,AROUT,BERGS
(使用STUFF去除開頭的逗號)
-- STUFF(原字串, 起始位置, 移除長度, 替換字串)):起始位置為1
Select STUFF(
(Select top 5 ',' + CustomerID
From dbo.Customers
For Xml Path(''))
, 1, 1, '')
結果:ALFKI,ANATR,ANTON,AROUT,BERGS
【兩個以上的資料表】
Select O.OrderID
, (
Select ProductID
From dbo.[Order Details] D
where D.OrderID = O.OrderID
For Xml Path('')
) as ProductIDList
from dbo.Orders O
Select O.OrderID
, (
Select ',' + CAST(ProductID as varchar)
From dbo.[Order Details] D
where D.OrderID = O.OrderID
For Xml Path('')
) as ProductIDList
from dbo.Orders O
留言列表