Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SQL Server result set into string

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]

like image 238
Zerotoinfinity Avatar asked Jan 27 '11 17:01

Zerotoinfinity


People also ask

Can we convert int to varchar in SQL?

Converting int to string/varchar using Cast() So, in the above example, we have declared a variable of integer data type and assigned a value to the variable. After this, we are using the Cast() function to convert the variable to the varchar data type of length 10.

What does convert () do in SQL?

The CONVERT() function converts a value (of any type) into a specified datatype.

What is CAST () and convert () functions in SQL Server?

The cast and convert functions provide similar functionality. They are used to convert a value from one data type to another. So let's take a look at a practical example. The example is developed in SQL Server 2012 using the SQL Server Management Studio.


2 Answers

Test this:

 DECLARE @result NVARCHAR(MAX)   SELECT @result = STUFF(                         (   SELECT ',' + CONVERT(NVARCHAR(20), StudentId)                              FROM Student                              WHERE condition = abc                              FOR xml path('')                         )                         , 1                         , 1                         , '') 
like image 57
ABI Avatar answered Sep 20 '22 14:09

ABI


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 
like image 20
Bonshington Avatar answered Sep 21 '22 14:09

Bonshington