views:

92

answers:

1

One category can have many products. I have to build StoredProcedure that returns all categories with some data from Products combined into one field:

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

ProductNames and ProductQuantities are varchar fields with combined (concatenated) field values from joined Product tables. This is what I have in 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 

I would also like to have Function, that returns "Product1,Product2" for input parameter idCategory=1, like this:

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

maybe one function that returns Table Result, so joining would be done only once, not in every Fn (because this is simplified example, in real app I have to have 4-5 combined fields, or even more in the future)?

How to write that SQL / SP & Fn? I'm using MS SQL2005

+2  A: 

There are several solutions for concatenating rows using SQL Server. See this, and this.

This query produces the result set you asked for:

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

Edited to add: This query produces the result:

idCategory  Name    ProductNames          ProductQuantities
1           Cat1    Product1, Product2    24, 32
2           Cat2    ProductX, ProductY    0, 61
Jamie Ide
i already found those examples through google, but don't know have to build Function that returns Table result, and how to include that results to SP results
Hrvoje
One of the links includes the code for such a function...
Tom H.
@Tom H but not for function with Table result
Hrvoje
@Hrvoje: I think you are having problem searching for your problem. The keyword you should search with is "Table-Valued" function
Sung Meister
@jamie I love seeing creaitive answer like this so that I can learn from it ad well
Sung Meister
no. it didn't work. I had to use COALESCE and several sql functions. But thanx for this example, i learned from it a lot
Hrvoje
@Hrvoje -- I actually created a database and populated it with the data from your question. This solution does work for the question as stated. I'll re-run it and add the query result to my answer.
Jamie Ide