2009-05-29 65 views
1

一個類別可以有許多產品。我要建立的StoredProcedure返回從產品的一些數據合併到一個字段中的所有類:結合字段加入表

 
SP Result: 
idCategory Name ProductNames   ProductQuantities 
1   Cat1 Procut1,Product2  24,32 
2   Cat2 ProductX,ProductY 0,61 

ProductNames和ProductQuantities是從加入產品表合併(連續)字段值VARCHAR字段。這是我在DB:

 
Category table: 
idCategory Name 
1   Cat1 
2   Cat2 

Product table: 
idProduct idCategory Name  Quantity 
1   1   Product1 24 
2   1   Product2 32 
3   2   ProductX 0 
4   2   ProductY 61 

我也想有功能,返回「產品1,產品2」爲輸入參數idCategory = 1,像這樣:

 
SELECT idCategory, 
     dbo.NamesFn(idCategory) AS ProductNames, 
     dbo.QuantitiesFn(idCategory) AS ProductQuantities 
FROM Category 

也許一個功能返回表結果,所以加入只能進行一次,而不是每個Fn(因爲這是一個簡化的例子,在真實應用程序中,我必須有4-5個組合字段,或者將來會有更多)?

如何編寫該SQL/SP & Fn?我正在使用MS SQL2005

回答

2

有幾種使用SQL Server連接行的解決方案。見thisthis

,該查詢產生的結果集,你問:

select c.idCategory, c.Name, 
    replace(
     (select p.Name as [data()] 
     from Product p 
    where p.idCategory = c.idCategory 
    for xml path ('') 
), ' ', ', ') as ProductNames, 
    replace(
     (select p.Quantity as [data()] 
     from Product p 
    where p.idCategory = c.idCategory 
    for xml path ('') 
), ' ', ', ') as ProductQuantities 
from Category c 

編輯補充: 此查詢產生的結果爲:

idCategory Name ProductNames   ProductQuantities 
1   Cat1 Product1, Product2 24, 32 
2   Cat2 ProductX, ProductY 0, 61 
+0

我已經發現,通過谷歌的例子,但不知道必須構建返回表結果的函數,以及如何將結果包含到SP結果中 – 2009-05-29 13:30:10