home


Create csv string from table entries
Author Nigel Rivett


Single string for all values in a table
create table tbl(id int, value varchar(10))
insert tbl select 1, 'a'
insert tbl select 1, 'b'
insert tbl select 1, 'c'

Required results
'a,b,c'

Method
declare @csv varchar(1000)
select @csv = coalesce(@csv+',','') + value
from tbl
select @csv

String for each id value in a table
create table tbl(id int, value varchar(10))
insert tbl select 1, 'a'
insert tbl select 1, 'b'
insert tbl select 1, 'c'
insert tbl select 2, 'a'
insert tbl select 2, 'b'

Required results

1, 'a,b,c'
2, 'a.b'

Easiest to create a function which creates the csv string
then

select id, dbo.csvtbl(id)
from tbl
group by id

the function will be something like

create function csvtbl
(@id as int)
returns varchar(1000)
AS
begin
declare @csv varchar(1000)
select @csv = coalesce(@csv+',','') + value
from tbl
where id = @id
return @csv
end
go


if you want a loop instead of the string concatenate in the function.

declare @x varchar(10), @maxx varchar(10)
select @x = '', @maxx = max(value) from tbl where id = @id
while @x < @maxx
begin
select @x = min(value) from tbl where id = @id and value > @x
select @csv = cocalesce(@csv+',','') + @x
end



home