Thursday, March 1, 2012

get Comma separated string for Column in Sql

Assuming i have table

Create Table shifts
(
RequestNo int, ShiftId int


and for each request number we want to get a comma separated string of shift ids associated with a particulare request



select SubString
( (SELECT ', ' + convert(varchar(1),p2.ShiftID )FROM shifts p2
FOR XML PATH('')),2,200000)


Happy Living ...
Happy Coding...
Happy Concepts

2 comments:

  1. Hi,

    I have value for record with a1;a=2;a=3;a=4 and another record with value b=1;b=2
    now i want to display the values of this two record has
    a=1
    a=2
    a=3
    a=4
    b=1
    b=2
    can you help me...?

    ReplyDelete
    Replies
    1. Assuming you have a table with name t1 and column name c1 and c1 has the record you have just mentioned above.

      declare @t1 as table ( c1 varchar(500))

      insert into @t1
      values('a=1;a=2'),('b=1;b=2')

      --declare another table @t2 to iterate through table @t1

      declare @t2 as table (rowindex int identity(1,1), c1 varchar(500))

      insert into @t2
      select c1 from @t1

      declare @loopcnt int=1

      --declare a @resulttable to use it as resultholder table
      declare @resultTable as table (resultColumn varchar(500))

      while( @loopcnt<=(select COUNT(*) from @t2))
      begin
      insert @resultTable
      select item from [dbo].[Split](( select top 1 c1 from @t2 where rowindex=@loopcnt ),';')
      set @loopcnt = @loopcnt +1
      end

      select * from @resultTable

      Note: use following link to create split function
      http://tryconcepts.blogspot.in/2011/11/split-value-in-sqlsever.html

      I hope this will help you.

      Delete