sql server results to comma delimited string 1

sql server results to comma delimited string

DECLARE @csv VARCHAR(MAX)
SELECT @csv = COALESCE(@csv + ',' ,'') + book_title from Test.dbo.Books where book_id IN ( 101, 102, 103);
SELECT @csv 

Output
Head First SQL, SQL Puzzler, T-SQL Fundamentals

Here is what the above code is Doing:
1. Declare a variable @csv of type VARCHAR(MAX)
2. Select the book_title from the Books table where the book_id is in the list of book_id’s (101, 102, 103)
3. Concatenate the book_title’s into the @csv variable
4. Select the @csv variable

Similar Posts