views:

38

answers:

2

I have an existing view that returns data in the following format.

option_name           product_id

XSMALL (2-6)          17854
SMALL (6-10)          17854
MEDIUM (10-14)      17854
LARGE                 18232

How do I return this data in a comma separated field formatted like this, based on sending a product_id to the function?

XSMALL (2-6), SMALL (6-10), MEDIUM (10-14)

I am using MS SQL 2k5.

+1  A: 

You can use FOR XML PATH in SQL Server 2005 and up:

CREATE FUNCTION dbo.GetProductNames(@ProductID int)
RETURNS TABLE
AS
SELECT
    Options = SUBSTRING((
        SELECT ', ' + o2.option_name
        FROM options AS o2
        WHERE o2.product_id = o1.product_id
        FOR XML PATH('')), 3, 1000)
FROM options AS o1
WHERE o1.product_id = @ProductID
Aaronaught
Thanks a bunch, can you wrap this in a UDF create statement, having trouble getting it to work.
jeff
@Aaronaught: while you're at it, can you make the tea. lol!
Mitch Wheat
Lol @Mitch... exact same code with a 3-line function header. :P
Aaronaught
SQL humor aside, thanks for the help
jeff
if the post was helpful how come you haven't upvoted? +1 from me.
Mitch Wheat
What's the SUBSTRING for?
OMG Ponies
I think this needs to be a scalar function since I am trying to use the returned value as a field in another query as part of a select statement. Can this be easily converted to a scalar function?
jeff
A: 

**

declare @option_name varchar(1000) select @option_name = isnull(@option_name+',','') + option_name from tablename select @option_name

**

anu