Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Insert a linebreak in varchar string

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?

like image 471
90abyss Avatar asked Apr 13 '16 19:04

90abyss


People also ask

How do I insert a line break in varchar Nvarchar string in SQL Server?

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.

How do you insert a line break in SQL query?

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. '+ CHAR(13)+CHAR(10) + 'Second line.

How do I split a string in SQL?

The STRING_SPLIT(string, separator) function in SQL Server splits the string in the first argument by the separator in the second argument. To split a sentence into words, specify the sentence as the first argument of the STRING_SPLIT() function and ' ' as the second argument. FROM STRING_SPLIT( 'An example sentence.


2 Answers

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

enter image description here

The results I got for your query are below( and they work) enter image description here

like image 147
DhruvJoshi Avatar answered Sep 22 '22 08:09

DhruvJoshi


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:

enter image description here

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:

enter image description here

enter image description here


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.';
like image 41
Lukasz Szozda Avatar answered Sep 21 '22 08:09

Lukasz Szozda