SQL: merging multiple row data in string 1

SQL: merging multiple row data in string

DECLARE @Names VARCHAR(8000) 
SELECT @Names = COALESCE(@Names + ', ', '') + 
    ISNULL(Name, 'N/A')
FROM People

Here is what the above code is Doing:
1. Declare a variable called @Names
2. Set the value of @Names to the result of the following:
a. If @Names is not null, concatenate a comma and a space to the end of it.
b. If the Name column is not null, return the value of the Name column.
c. If the Name column is null, return the string ‘N/A’.
3. Repeat step 2 for each row in the People table.

The result of the above code is that @Names will contain a comma-separated list of all the names in the People table.

Similar Posts