The World’s Leading Microsoft .NET Magazine
   
 
timstall

Donate Today!

Search Box

 

Calendar

««Jul 2008»»
SMTWTFS
  
1
2
3
4
5
67
8
9
10
1112
13
14
15
16
17
18
19
202122
23
24
25
26
2728293031

My RSS Feeds








Mailing List

Most Popular Tags

                                                           

SQL Tip: Concat entire column into a single CSV string

posted Thursday, 2 November 2006

Sometimes in SQL, you'll want to concat an entire column's values into a single string.

For example, say you have a parent-child relationship (like state-city, or entity-code), and in a parent's list page, you want to display a column with the CSV string of all the children.

State City
IL Chicago
IL Springfield
IL Rockford
WI Madison

You can concatenate a list of values into a CSV string like "Chicago, Springfield, Rockford" by continually selecting into the same variable:

        declare @sCsv varchar(1000)
        set @sCsv = ''

        select @sCsv = @sCsv + City + ', '
        from MyTable
        where State = 'IL'; --any filter clause here

        --remove final ","
        if (Len(@sCsv) > 1)
                select @sCsv = substring(@sCsv,1,len(@sCsv)-1)
        return @sCsv

tags:  

links: digg this    technorati    




1. Awa left...
Tuesday, 5 December 2006 4:19 pm

this is really interesting to me. However is it possible to do it for all state. For instance:

State City IL Chicago, Springfield, etc WI Madison, etc

Thanks, Awa


2. Tim Stall left...
Monday, 11 December 2006 10:43 am

Offhand I don't know a fast-eprformance way, but you could do something like this:

  • select @sCsv = @sCsv + State + ': ' + GetAllCitites(State) + ', '

  • from (Select distinct State from MyTable) as T1

  • order by State

1 - select to get just the states first 2 - Write a function GetAllCities(State) which takes a state and then applies its own loop to return a CSV list of all the appropriate cities.

However, warning that this will probably perform slowly, but functionally it does what you want.