2012-09-15 189 views
11
 
Customer Table 
-------------- 
ID Name 
1 James 
2 Peter 
 
Order Table 
--------------- 
OrderId CustId 
100  1 
101  1 
102  2 

我怎麼能寫一個返回這樣逗號在一列分隔值 - SQL SERVER

 
ID,Name,ListofOrders 
1,James,"100,101" 
2,Peter,"102" 

在Sybase東西,我有一個函數調用列表,我可以使用它,但我查詢不發現SQL Server中的類似功能

+1

[Here](http://bradsruminations.blogspot.com/2009/10/making-list-and-checking -it-twice.html),您可以找到複雜的解決方案和解釋。 – WojtusJ

+0

哇,這是一個複雜的解決方案:) Sybase的LIST功能要好得多。想知道爲什麼SQL服務器沒有這個簡單的東西 – JanetOhara

回答

12

請嘗試:

select ID, [Name], 
(select OrderID+',' from OrderTable where CustID=ID 
group by OrderID for xml path('')) AS ListOfOrders 
From CustomerTable 
+0

謝謝你Techdo – JanetOhara

1

創建一個用戶定義函數如下圖所示

CREATE FUNCTION [dbo].[CommaSeperatedOrderIDs](@CustId INT) returns varchar(Max) 
AS 
BEGIN 

DECLARE @CommaSeperatedValues VARCHAR(MAX) 
SELECT @CommaSeperatedValues = COALESCE(@CommaSeperatedValues+',' , '') + OrderID 
FROM OrderTable WHERE CustId = @CustId 
RETURN @CommaSeperatedValues 

END 

然後,

select ID, [Name], ([dbo].[CommaSeperatedOrderIDs](ID)) AS ListofOrders 
From CustomerTable 
0

從Sheikh Haris'link添加全部細節。

對於這個表:

enter image description here

要獲得輸出,如:

enter image description here

使用下面的SQL:

SELECT field1, 
    Substring(convert(varchar(100), 
    (
    SELECT (', ' + field2) 
     FROM #test t2 
     WHERE t1.field1 = t2.field1 
     ORDER BY field1, field2 
    FOR XML PATH('') 
        )), 3, 1000) 
FROM #test t1 
GROUP BY field1 

我添加了一個轉換函數的子字符串,以便顯示WIDEMEMO字段(SQL Server)