line breaks lost in sql server

SSMS replaces linebreaks with spaces in the grid output. If you use Print to print the values (will go to your messages tab) then the carriage returns will be displayed there if they were stored with the data.

Example:

SELECT 'ABC' + CHAR(13) + CHAR(10) + 'DEF'
PRINT 'ABC' + CHAR(13) + CHAR(10) + 'DEF'

The first will display in a single cell in the grid without breaks, the second will print with a break to the messages pane.

A quick and easy way to print the values would be to select into a variable:

DECLARE @x varchar(100);
SELECT @x = 'ABC' + CHAR(13) + CHAR(10) + 'DEF';
PRINT @x;

No need to replace string input\output, you need just pick up correct option:

Tools -> Options...

> Query Results 
  > SQL Server 
    > Results to Grid 

set "Retain CR\LF on copy or save" to true.

And don't forget to restart your management studio!

according Charles Gagnon answer


Update a couple years later.

As described here, one solution to preserve viewing linebreaks in SSMS is to convert the output to XML:

SELECT * FROM (
  SELECT * from ErrorLog ORDER BY ErrorDate
) AS [T(x)] FOR XML PATH

Fortunately, if you have SSMS 2012, this is no longer an issue, as line breaks are retained.

Tags:

Sql Server