I want to select a set of data into a single string, but I still want each item on its own line (I will then put it in Crystal Reports, and it will be faster than using tons of subreports.)
So, I have the following data:
ID Assessor
1 Black
1 Jones
and I want to query it, and return a single string that looks like:
Black
Jones
if I do a select using coalesce, I can make it comma or semi-colon delimited, but not linefeed delimited:
BEGIN
declare @Assessors NVarChar(max)
Declare @LineFeed varchar(10)
DECLARE @Return varchar(10)
Set @LineFeed = char(10)
SET @Return = char(13)
Select @Assessors = COALESCE(@Assessors + ', ', '') + a.Assessor
FROM dbo.Assessment a
Where (@ID = a.ID)
Return @Assessors
END
in that, the function will return 'Black, Jones'. But if I change the line to
Select @Assessors = COALESCE(@Assessors + @Return + @LineFeed, '') + a.Assessor
it returns 'Black Jones' -- it doesn't put in a linefeed or return, just a space.
I guess I don't have to use Coalesce, but I've tried just standard concatenating, and that won't put it in either. I've got this in a function right now, but plan on putting it as part of a stored procedure, so it's faster.
You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.
Insert SQL carriage return and line feed in a string We can use the following ASCII codes in SQL Server: Char(10) – New Line / Line Break. Char(13) – Carriage Return. Char(9) – Tab.
SQL Server ' AS 'New Line' -- using carriage return: CHAR(13) SELECT 'First line. '+ CHAR(13) + 'Second line. ' AS 'New Line' -- Using both: CHAR(13)+CHAR(10) SELECT 'First line.
You can use the COALESCE expression to evaluate records for multiple values and return the first non-NULL value encountered, in the order specified.
CHAR(13)+CHAR(10)
will produce line breaks, I do this all the time in production code.
I ran your code, and it produces line breaks on my system. IN SSMS, switch your view to "Results to Text" from "Results to Grid" and you will see the line breaks.
use the Char function to insert:
Tab char(9)
Line feed char(10)
Carriage return char(13)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With