Separating the values of a column with a comma

  • I have a table like this:

    Column1    Column2   Column3

    1               50.00       12345

    2               100.00      23345

    2                10           55555

    -----------------------------

    I need it like this:

    Column2      Column3

    50.00          12345

    100.00         23345, 55555   

    Iam writing a stored procedure in SQL Server. Please let me know how to do this.

     

    thanks,

    fz

             

  • What has happened to the "10" in column2?

     

  • This seems to work. It assumes that your table is called cursor_test:

    create procedure pivot_my_table
    as
     declare mycursor CURSOR for
      select col1,col2,col3 from cursor_test
     
     declare @col1 int, @col2 decimal, @col3 decimal
     
     if exists (select * from #temp)
      DROP TABLE #temp
     select distinct col1, cast(null as varchar(8000)) as col2, cast(null as varchar(8000)) as col3
     into #temp
     from cursor_test
     
     
     open mycursor
     
     fetch next from mycursor 
     into @col1, @col2, @col3
     
     while @@FETCH_STATUS = 0
     BEGIN
      update #temp
      set col2 = ISNULL(col2 + ',', '') + cast(@col2 as varchar),
       col3 = ISNULL(col3 + ',', '') + cast(@col3 as varchar)
      where col1 = @col1
     
      fetch next from mycursor 
      into @col1, @col2, @col3
     END
     
     CLOSE mycursor
     DEALLOCATE mycursor
     
     select *
     from #temp
    

    Hope that helps

     

    -Jamie

     

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply