SQL: Insert a linebreak in varchar string - sql

I've searched StackOverflow for all the possible solutions concerning how to insert a linebreak in a SQL text string. I've referred this link but to no avail. How to insert a line break in a SQL Server VARCHAR/NVARCHAR string
But none of the solutions are working for me.
This is what I'm trying to do:
insert into sample (dex, col)
values (2, 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.')
But this is the output generated: (Select Col from sample where dex = 2)
This is line 1. This is line 2.
This is the output that I desire:
This is line 1.
This is line 2.
I'm using SQL server and SSMS if that helps.
Any ideas why it isn't working?

Well your query works perfectly fine.
SSMS by default shows all query out put in the grid view, which does not display the line break character.
To see it you can switch to text view using cntrl + T shortcut or like below
The results I got for your query are below( and they work)

It works perfectly:
CREATE TABLE sample(dex INT, col VARCHAR(100));
INSERT INTO sample(dex, col)
VALUES (2, 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.');
SELECT *
FROM sample;
LiveDemo
Output:
The "problem" is SSMS grid view that skips newline characters (and others too). Otherwise you will get different rows height like in Excel.
You could observe the same behaviour in SEDE.
LiveDemo-SEDELiveDemo-SEDE-TextView
Output:
You could compare it using:
SELECT 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.';
PRINT 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.';

The CR/LF chars are there, it's just that in the format of your output, they are being ignored.
I've created a fiddle to illustrate this, with 2 VARCHAR columns. In the first one I insert the text with no CR/LF, in the second I include them
CREATE TABLE sample (dex INT, colnocr VARCHAR(50), col VARCHAR(50)) ;
insert into sample (dex, colnocr, col) values
(2,
'This is line 1.' + 'This is line 2.',
'This is line 1.' + CHAR(13) + CHAR(10) + 'This is line 2.'
)
;
if you run the query
SELECT * FROM sample
The result in plain text are:
| dex | colnocr | col |
|-----|--------------------------------|----------------------------------|
| 2 | This is line 1.This is line 2. | This is line 1.
This is line 2. |
but if you run it in tabular :
dex colnocr col
2 This is line 1.This is line 2. This is line 1. This is line 2.
Check it : SqlFiddleDemo

A bit late to this discussion, but in SSMS 2016, there is an option on the Tools | Options menu under Query Results / SQL Server / Results to Grid called "Retain CR/LF on copy or save". Checking this box will allow you to copy values from a cell in a grid result to, say, another query window and still have the line breaks.

Related

How to give line break between two strings in single column?

I have used single column to store multiple comments . In that column i have to store every comments in new line so that i can able to differentiate the comments.
I have tried CHAR(13) and CHAR(13) + CHAR(10) between two strings . But it's not working.I shown the records in single line.
Tried code:
DECLARE #text NVARCHAR(100)
SET #text = 'This is line 1.' + CHAR(13) + 'This is line 2.'
SELECT #text
Please suggest the solution.
You can use PRINT statement instead of SELECT statement to achieve what you want.
For example, you can use any of the followings:
PRINT 'This is line 1.' + CHAR(13) + 'This is line 2.'
Or
PRINT 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'
Or
PRINT CONCAT(N'This is line 1.', 0xd000a, N'This is line 2.')
UPDATE: According to this forum,
You can not see char(13) in SSMS in the Grid format. This character is there and you can see it if you output the result into report, into text, into Excel. But in SSMS grid you can not see this character.
You can change settings from "Results to Grid" to "Results to Text"
from menu using the following steps:
Query -> Results to -> Results to Text
Then you will be able to view line break between two strings using any of the followings
SELECT 'This is line 1.' + CHAR(13) + 'This is line 2.'
Or
SELECT 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'
Or
SELECT CONCAT(N'This is line 1.', 0xd000a, N'This is line 2.')
another way
select concat(N'This is line 1.', 0xd000a, N'This is line 2.')
or
select 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'

How to replace multiple Line Breaks with single Line break from nvarchar string in SQL Server [duplicate]

This question already has an answer here:
How do I replace a pattern using T-SQL?
(1 answer)
Closed 7 years ago.
I have a column 'CN_Text' of nvarchar type which will store notes with multiple line breaks.
Example -
Aaaaaaaa....
Bbbbb
Cccccccc
I want to replace multiple consecutive line breaks with single line break. Like
Aaaaaaaa....
Bbbbb
Ccccccccc
How I can replace this multiple line breaks with single line break?
First replace all the new line to a different set of characters then replace those characters with new line as below.
select string = replace(replace(replace('Aaaaaaaa....
Bbbbb
Cccccccc','
','<>'),'><',''),'<>','
')
I think you are looking this:
DECLARE #A nvarchar(500)
SET #A = 'Aaaaaaaa....
Bbbbb
Cccccccc';
SET #A =
replace(replace(replace(
replace(
replace(#A,
CHAR(13)+CHAR(10),' '),
' ','<>'),'><',''),'<>',' '),
' ',CHAR(13)+CHAR(10));
PRINT #A
First remove all the break lines in your text, later change the consecutive spaces with just one, and finally change the space by the break line you need.

new line into SELECT query sql server 2005

I want to do a new line in my sql select
I try this but it won't work
SELECT '1' + char(13) + '2'
AND
SELECT '1' + char(13) + char(10) + '2'
it always return 12
thanks for your answers
in fact I try to export data from sql to TXT file
but when I execute the bcp file it return concatenate rows
The new line is in your result. If you copy and paste the result from your query into notepad, for example, you'll see 1, new line, 2. The reason you see 1 2 in your result in the results window is because you are returning 1 row. Notice that len('1' + char(13) + char(10) + '2') = 4, that is because your chars are present, it's just represented as a single row (with multiple lines in the row).
That's just the way SSMS displays the results. If you copy the result out into Notepad, or as Lamak says choose Results to Text you should see the newlines in place.

LOAD DATA INFILE (*.csv) - ignore empty cells

I'm about to import a large (500 MB) *.csv file to a MySQL database.
I'm as far as that:
LOAD DATA INFILE '<file>'
REPLACE
INTO TABLE <table-name>
FIELDS
TERMINATED BY ';'
OPTIONALLY ENCLOSED BY '"'
IGNORE 1 LINES ( #Header
<column-name1>,
<column-name2>,
...
);
I have a problem with one of the coluns (it's data type is int) - I get an error Message:
Error Code: 1366 Incorrect integer value: ' ' for column at row
I looked at this line in the *.csv-file. The cell that causes the error has just a whitespace inside (like this: ...; ;...).
How can I tell SQL to ignore whitespaces in this column?
As the *.csv-file is very big and I have to import even bigger ones afterwards, I'd like to avoid editing the *.csv-file; I'm looking for a SQL-solution.
Add a SET COLUMN like so:
LOAD DATA INFILE 'file.txt'
INTO TABLE t1
(column1, #var1)
SET column2 = #var1/100;
You need to replace the #var1/100 with an expression that handles the 'space' and convert to -Infinity or 0 or 42... not sure..
This answer was originally included in the question as an edit by #speendo; I have converted it into a proper answer.
The solution is:
LOAD DATA INFILE '<file>'
REPLACE
INTO TABLE <table-name>
FIELDS
TERMINATED BY ';'
OPTIONALLY ENCLOSED BY '"'
IGNORE 1 LINES ( #Header
<column-name1>,
<column-name2>,
#var1 #the variable that causes the problem
...
)
SET <column-name-of-problematic-column> = CASE
WHEN #var1 = ' ' THEN NULL
ELSE #var1
END
;

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

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.
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.'
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.
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'"
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
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 :)
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.')
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