Q: How do I retrieve values from a table and store the results in a string?

Learn how to retrieve values from a table and store the results.

Bill McEvoy

August 27, 2008

1 Min Read
ITPro Today logo

Q: How do I retrieve values from a table and store the results in a string?

A: The following code provides a simple yet effective method for retrieving values from a table and storing the results in a string, 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

You need to initialize your string to a non-NULL value, or the string will end up as NULL, which is the default behavior of NULLs and string concatenation.

—Bill McEvoy

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like