SQL String Concatenation

SQL String Concatenation

Have you ever wanted to retrieve a list of values from a table, storing the results in a string?

Here is simple yet effective method without having to rely on cursors, while loops, or other complex structures.

declare @string varchar(8000)
select @string = ''

select @string = @string + MyColumn
  from MyTable

print @string

It is important to initialize your string to a non-NULL value, otherwise your string will end up as NULL, which is the default behavior of NULLs and string contcatenation.

Give it a try, it works like a charm.  😎

Stefan Pejcic
Join the discussion

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.