61

I am getting the result in SQL Server as

SELECT StudentId FROM Student WHERE condition = xyz

I am getting the output like

StudentId
1236

7656

8990
........

The output parameter of the stored procedure is @studentId string and I want the return statement as

1236, 7656, 8990.

How can I convert the output in the single string?

I am returning single column [ie. StudentId]

p.campbell
  • 98,673
  • 67
  • 256
  • 322
Zerotoinfinity
  • 6,290
  • 32
  • 130
  • 206

11 Answers11

79

Test this:

 DECLARE @result NVARCHAR(MAX)

 SELECT @result = STUFF(
                        (   SELECT ',' + CONVERT(NVARCHAR(20), StudentId) 
                            FROM Student 
                            WHERE condition = abc 
                            FOR xml path('')
                        )
                        , 1
                        , 1
                        , '')
ABI
  • 1,714
  • 15
  • 14
66
DECLARE @result varchar(1000)

SELECT @result = ISNULL(@result, '') + StudentId + ',' FROM Student WHERE condition = xyz

select substring(@result, 0, len(@result) - 1) --trim extra "," at end
Justin
  • 954
  • 4
  • 22
  • 44
Bonshington
  • 3,970
  • 2
  • 25
  • 20
  • 2
    I've just tried this code and it works. Just minor adjustment: select substring(@result, 1, len(@result) -1 ) to remove the extra "," – Eden Nov 19 '12 at 10:23
  • 3
    Tried this and the last line doesn't work correctly in SQL Server 2008. `substring(@result, 1, len(@result) )` removes the trailing comma, whereas the version above removes the character before the comma as well. :) – async May 29 '14 at 12:06
  • 2
    should be `substring(@result, 1, len(@result) - 1)` http://msdn.microsoft.com/en-GB/library/ms187748.aspx – Robino Sep 18 '14 at 19:07
  • If the StudentId is coming from a non varchar column, you will probably get a conversion exception. You need to use the CONCAT function to do proper concatenation. See answer below. – pistol-pete Mar 28 '17 at 21:49
12

Use the COALESCE function:

DECLARE @StudentID VARCHAR(1000)
SELECT @StudentID = COALESCE(@StudentID + ',', '') + StudentID
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select @StudentID
Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Saloni
  • 129
  • 1
  • 2
  • If the StudentId is coming from a non varchar column, you will probably get a conversion exception. You need to use the CONCAT function to do proper concatenation. See answer below. – pistol-pete Mar 28 '17 at 21:51
8

Both answers are valid, but don't forget to initializate the value of the variable, by default is NULL and with T-SQL:

NULL + "Any text" => NULL

It's a very common mistake, don't forget it!

Also is good idea to use ISNULL function:

SELECT @result = @result + ISNULL(StudentId + ',', '') FROM Student
Community
  • 1
  • 1
Alex
  • 797
  • 10
  • 30
  • 2
    Reference to "Both answers" is kind of useless as answers move around and there are more than 2. – Thronk Apr 26 '18 at 15:36
6

Use the CONCAT function to avoid conversion errors:

DECLARE @StudentID VARCHAR(1000)
SELECT @StudentID = CONCAT(COALESCE(@StudentID + ',', ''), StudentID)
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select @StudentID
pistol-pete
  • 1,213
  • 17
  • 13
2

The following is a solution for MySQL (not SQL Server), i couldn't easily find a solution to this on stackoverflow for mysql, so i figured maybe this could help someone...

ref: https://forums.mysql.com/read.php?10,285268,285286#msg-285286

original query...

SELECT StudentId FROM Student WHERE condition = xyz

original result set...

StudentId
1236
7656
8990

new query w/ concat...

SELECT group_concat(concat_ws(',', StudentId) separator '; ') 
FROM Student 
WHERE condition = xyz

concat string result set...

StudentId
1236; 7656; 8990

note: change the 'separator' to whatever you would like

GLHF!

greenhouse
  • 1,231
  • 14
  • 19
1

This one works with NULL Values in Table and doesn't require substring operation at the end. COALESCE is not really well working with NULL values in table (if they will be there).

DECLARE @results VARCHAR(1000) = '' 
SELECT @results = @results + 
           ISNULL(CASE WHEN LEN(@results) = 0 THEN '' ELSE ',' END + [StudentId], '')
FROM Student WHERE condition = xyz

select @results
1

The answer from brad.v is incorrect! It won't give you a concatenated string.

Here's the correct code, almost like brad.v's but with one important change:

DECLARE @results VarChar(1000)
  SELECT @results = CASE
     WHEN @results IS NULL THEN CONVERT( VarChar(20), [StudentId])
     ELSE @results + ', ' + CONVERT( VarChar(20), [StudentId])
  END
FROM Student WHERE condition = abc;

See the difference? :) brad.v please fix your answer, I can't do anything to correct it or comment on it 'cause my reputation here is zero. I guess I can remove mine after you fix yours. Thanks!

1

Use STRING_AGG:

SELECT STRING_AGG(sub.StudentId, ',') FROM  
(select * from dbo.Students where Name = 'Test3') as sub

If you want to use e.g ORDER BY:

SELECT STRING_AGG(sub.StudentId, ',') WITHIN GROUP(Order by StudentId) FROM  
(select * from dbo.Students where Name = 'Test3') as sub
Przemysław Kleszcz
  • 536
  • 1
  • 7
  • 13
0

or a single select statement...

DECLARE @results VarChar(1000)
SELECT @results = CASE
     WHEN @results IS NULL THEN CONVERT( VarChar(20), [StudentId])
     ELSE ', ' + CONVERT( VarChar(20), [StudentId])
   END
FROM Student WHERE condition = abc;
brad.v
  • 317
  • 1
  • 2
  • 10
0

Assign a value when declaring the variable.

DECLARE @result VARCHAR(1000) ='';

SELECT @result = CAST(StudentId AS VARCHAR) + ',' FROM Student WHERE condition = xyz
Delmirio Segura
  • 1,651
  • 1
  • 9
  • 5