/* This is one method of using a variable to take a single column result set and return
it as a single VARCHAR string.
You start with code like this:
SELECT description
FROM T_CAMPAIGN
WHERE description like '2018 Individual%'
which will give you a normal results set like this:
description
2018 Individual
2018 Individual Institute
2018 Individual Priorities
however, you can use a varchar variable to concatenate this all into a single string like this:
Single String Results
2018 Individual, 2018 Individual Institute, 2018 Individual Priorities,
*/
-- declare the @kstring variable
DECLARE @kstring varchar(4000)
-- set the variable to '' (making it no longer NULL - if you don't do this, your results will be NULL)
SELECT @kstring = ''
/* set the value of @kstring to the current value ('') and concatenate the multi-row results from description.
If you start with a single string (in this case ''), concatenating the multi-row results will
place those results into a single character string.
Using 'SELECT @kstring = @kstring + description from T_CAMPAIGN' will result in all description values being placed
together into a single string with no spaces or delimiters between them.
In the example below, the RTRIM funciton is added around 'description' to trim trailing spaces from the values in description,
and concatenating ', ' adds a comma and a space in-between the values, giving you a nice readable format.
*/
SELECT @kstring = @kstring + RTRIM(description) + ', '
FROM T_CAMPAIGN
WHERE description like '2018 Individual%'
-- select @kstring to see everything placed into a single string
SELECT @kstring AS 'Single String Results'
/*
Results from the code above:
Single String Results
2018 Individual, 2018 Individual Institute, 2018 Individual Priorities,
*/