Anatoly Lubarsky Logo
MSSQL, .NET, Design. Life and Music

HowTo Convert Table Values to Comma-Delimited String

We have 2 tables related as one-to-many. How can we fetch parent table field, and child table values comma-delimited ? The function below demonstrates a technique how to convert table values into comma-delimited string with one query.


ALTER FUNCTION F_GET_STR
(@p_order_id int)
RETURNS varchar(1000)
AS
    BEGIN
 
    DECLARE @p_str VARCHAR(1000)
    SET @p_str = ''

    SELECT @p_str = @p_str + ',' + CAST(productid AS VARCHAR(6))
      FROM [order details]
     WHERE orderid = @p_order_id

    RETURN @p_str

END

Use this way:


    SELECT orderid
          ,dbo.F_GET_STR(orderid)
      FROM orders

Related Posts:

Friday, April 02, 2004 4:36 AM

Comments

# T-SQL 2005: One-to-many comma separated

11/14/2005 12:44 AM by Anatoly Lubarsky: Weblog

If your feedback doesn't appear right away, please be patient as it may take a few minutes to publish.

Post a Comment

Protected by CAPTCHAEnter the code you see
Name (*)  
E-mail (*)  
Url
Remember

Comment (*)