I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question.
-
10To test your output, if using SSMS make sure the option Retain CR/LF on copy or save is checked, else all pasted results will loose the line feed. You find this at settings, query results, sql server, results to grid.– Stefanos ZilellisNov 9, 2018 at 10:19
-
1@StefanosZilellis and make sure to open a new query window for the setting changes to take effect.– Don CheadleMay 16, 2019 at 20:09
11 Answers
char(13)
is CR
. For DOS-/Windows-style CRLF
linebreaks, you want char(13)+char(10)
, like:
'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'
-
37
-
8@Nima: Some applications will use one or the other or both to show a new line, however many applications you may output this text to will require both do appear in succession to signify a new line. I find it safe to use both. You can list here which of your apps it doesn't work for. I prefer the CHAR(0x0D) + CHAR(0x0A) hexadecimal values myself, but to each their own. Mar 27, 2013 at 7:02
-
2I used this method successfully, but ran into a problem with it: once you have more than about 480
+
, SQL Server will start complaining that your query is too deeply nested. My solution was instead to use Rob Cooper's answer instead, but with a much longer and more obscure token. Apr 21, 2015 at 11:40 -
8Providing \r\n would mean acknowledgement that regular expressions exist and that there are users capable of understanding and using them.– wwmbesJun 30, 2016 at 8:30
-
10@HBlackorby \r and \n predate Java-anything by decades with their use in C; and are standard in Python, PHP, Ruby, C++, C#, etc...– UueerdoOct 18, 2017 at 23:29
I found the answer here: http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/
You just concatenate the string and insert a CHAR(13)
where you want your line break.
Example:
DECLARE @text NVARCHAR(100)
SET @text = 'This is line 1.' + CHAR(13) + 'This is line 2.'
SELECT @text
This prints out the following:
This is line 1.
This is line 2.
-
21
-
3BTW: You can also use
NCHAR(0x1234)
to get a unicode character. Not necessary for inserting line breaks, but can come in handy if one must insert/search for unicode characters. Oct 2, 2014 at 12:33 -
3In SQL Server 2016, I only see it print the two lines if I use
print
instead ofselect
, such as:DECLARE @text NVARCHAR(100); SET @text = 'This is line 1.' + CHAR(13) + 'This is line 2.'; print @text;
Jan 19, 2017 at 19:10 -
15To test your output, if using SSMS make sure the option Retain CR/LF on copy or save is checked, else all pasted results will loose the line feed. You find this at settings, query results, sql server, results to grid. May 16, 2019 at 20:18
-
4What @DonCheadle said, AND you may have to close the query tab and re-open it for that setting to take effect. ;) Mar 18, 2020 at 23:30
Another way to do this is as such:
INSERT CRLF SELECT 'fox
jumped'
That is, simply inserting a line break in your query while writing it will add the like break to the database. This works in SQL server Management studio and Query Analyzer. I believe this will also work in C# if you use the @ sign on strings.
string str = @"INSERT CRLF SELECT 'fox
jumped'"
-
17In other words, the syntax of the SQL language simply allows raw line feeds in strings literals. It works this way in all engines I've tried (SQL Server, Oracle, MySQL, PostgreSQL and SQLite). Feb 13, 2014 at 15:32
-
sometimes this randomly quits working if you use it in stored procedures– DaFi4Nov 20, 2019 at 12:20
All of these options work depending on your situation, but you may not see any of them work if you're using SSMS (as mentioned in some comments SSMS hides CR/LFs)
So rather than driving yourself round the bend, Check this setting in
Tools
|
Options
-
7I'm on v18.2 of SSMS and I had trouble getting this setting to stick. I had to check it on, then exit SSMS and restart. And make sure you only have 1 instance of SSMS running. The second instance will overwrite the setting w/ the original value. But eventually I was successful. +1 Jul 21, 2020 at 13:42
-
3Also note, If you output to Text instead of to Grid then the CR/LF will be preserved as expected without having to make any changes to the application options. Sep 30, 2021 at 9:52
-
1
Run this in SSMS, it shows how line breaks in the SQL itself become part of string values that span lines :
PRINT 'Line 1
Line 2
Line 3'
PRINT ''
PRINT 'How long is a blank line feed?'
PRINT LEN('
')
PRINT ''
PRINT 'What are the ASCII values?'
PRINT ASCII(SUBSTRING('
',1,1))
PRINT ASCII(SUBSTRING('
',2,1))
Result :
Line 1
Line 2
Line 3
How long is a blank line feed?
2
What are the ASCII values?
13
10
Or if you'd rather specify your string on one line (almost!) you could employ REPLACE()
like this (optionally use CHAR(13)+CHAR(10)
as the replacement) :
PRINT REPLACE('Line 1`Line 2`Line 3','`','
')
Following a Google...
Taking the code from the website:
CREATE TABLE CRLF
(
col1 VARCHAR(1000)
)
INSERT CRLF SELECT 'The quick brown@'
INSERT CRLF SELECT 'fox @jumped'
INSERT CRLF SELECT '@over the '
INSERT CRLF SELECT 'log@'
SELECT col1 FROM CRLF
Returns:
col1
-----------------
The quick brown@
fox @jumped
@over the
log@
(4 row(s) affected)
UPDATE CRLF
SET col1 = REPLACE(col1, '@', CHAR(13))
Looks like it can be done by replacing a placeholder with CHAR(13)
Good question, never done it myself :)
-
4But if the text has an email address in it? "[email protected]" becomes "jon bob.com" (with a newline in the e-dress) Jan 16, 2015 at 15:52
-
4@ChrisNash then use a different placeholder (e.g. "|", "~", or multiple characters, "!#!"). See this answer below: stackoverflow.com/a/31179/179311.– bradlis7Mar 25, 2015 at 19:29
-
1"CONCAT (CHAR(13) , CHAR(10))" ("\r\n") would be better for windows environment, which I assume is the case (SQL Server) cs.toronto.edu/~krueger/csc209h/tut/line-endings.html– d.popovMar 29, 2016 at 7:39
-
This is non-deterministic. A table is defined as an unordered set of records. There is no guarantee that the database engine will return the records in the order inserted. Without a second column to preserve the order in some way (a simple
IDENTITY()
would work) and anORDER BY
in your output query, the server will return the records in whichever order it finds convenient. That may be the same order they were inserted, but the server is allowed to do it however it wants to without anORDER BY
. Sep 23, 2020 at 12:25
I got here because I was concerned that cr-lfs that I specified in C# strings were not being shown in SQl Server Management Studio query responses.
It turns out, they are there, but are not being displayed.
To "see" the cr-lfs, use the print statement like:
declare @tmp varchar(500)
select @tmp = msgbody from emailssentlog where id=6769;
print @tmp
I'd say
concat('This is line 1.', 0xd0a, 'This is line 2.')
or
concat(N'This is line 1.', 0xd000a, N'This is line 2.')
-
2Also check the SSMS configuration on @Trubs answer: stackoverflow.com/a/59189881/386619 Jul 21, 2020 at 13:39
-
Here's a C# function that prepends a text line to an existing text blob, delimited by CRLFs, and returns a T-SQL expression suitable for INSERT
or UPDATE
operations. It's got some of our proprietary error handling in it, but once you rip that out, it may be helpful -- I hope so.
/// <summary>
/// Generate a SQL string value expression suitable for INSERT/UPDATE operations that prepends
/// the specified line to an existing block of text, assumed to have \r\n delimiters, and
/// truncate at a maximum length.
/// </summary>
/// <param name="sNewLine">Single text line to be prepended to existing text</param>
/// <param name="sOrigLines">Current text value; assumed to be CRLF-delimited</param>
/// <param name="iMaxLen">Integer field length</param>
/// <returns>String: SQL string expression suitable for INSERT/UPDATE operations. Empty on error.</returns>
private string PrependCommentLine(string sNewLine, String sOrigLines, int iMaxLen)
{
String fn = MethodBase.GetCurrentMethod().Name;
try
{
String [] line_array = sOrigLines.Split("\r\n".ToCharArray());
List<string> orig_lines = new List<string>();
foreach(String orig_line in line_array)
{
if (!String.IsNullOrEmpty(orig_line))
{
orig_lines.Add(orig_line);
}
} // end foreach(original line)
String final_comments = "'" + sNewLine + "' + CHAR(13) + CHAR(10) ";
int cum_length = sNewLine.Length + 2;
foreach(String orig_line in orig_lines)
{
String curline = orig_line;
if (cum_length >= iMaxLen) break; // stop appending if we're already over
if ((cum_length+orig_line.Length+2)>=iMaxLen) // If this one will push us over, truncate and warn:
{
Util.HandleAppErr(this, fn, "Truncating comments: " + orig_line);
curline = orig_line.Substring(0, iMaxLen - (cum_length + 3));
}
final_comments += " + '" + curline + "' + CHAR(13) + CHAR(10) \r\n";
cum_length += orig_line.Length + 2;
} // end foreach(second pass on original lines)
return(final_comments);
} // end main try()
catch(Exception exc)
{
Util.HandleExc(this,fn,exc);
return("");
}
}
This is always cool, because when you get exported lists from, say Oracle, then you get records spanning several lines, which in turn can be interesting for, say, cvs files, so beware.
Anyhow, Rob's answer is good, but I would advise using something else than @, try a few more, like §§@@§§ or something, so it will have a chance for some uniqueness. (But still, remember the length of the varchar
/nvarchar
field you are inserting into..)
In some special cases you may find this useful (e.g. rendering cell-content in MS Report )
example:
select * from
(
values
('use STAGING'),
('go'),
('EXEC sp_MSforeachtable
@command1=''select ''''?'''' as tablename,count(1) as anzahl from ? having count(1) = 0''')
) as t([Copy_and_execute_this_statement])
go
-
Can you add some more explanation, I have no idea how this works or how to use it Sep 24, 2020 at 19:11
-
1this statement delivers not a string with CR\LF in it, but a little table with one column ( named [Copy_and_execute_this_statement] ) and three rows. This is perhaps suitable for consumers, which swallow CR\LF but can consume tables ( e.g. MS Report ) another simple example would be " select * from ( values ( 'Adam'),('Eva')) as t([some_name])"– cjonasSep 26, 2020 at 16:47