SQL: Insert a linebreak in varchar string

后端 未结 4 1083
走了就别回头了
走了就别回头了 2021-01-04 08:11

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 inser

相关标签:
4条回答
  • 2021-01-04 08:37

    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

    0 讨论(0)
  • 2021-01-04 08:39

    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.

    0 讨论(0)
  • 2021-01-04 08:52

    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)

    0 讨论(0)
  • 2021-01-04 08:56

    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.';
    
    0 讨论(0)
提交回复
热议问题