line breaks lost in sql server

后端 未结 7 1469
心在旅途
心在旅途 2020-12-18 18:02

I am entering error information into an ErrorLog table in my database. I have a utility class to do this:

ErrorHandler.Error(\"Something has broken!!\\n\\nDe         


        
相关标签:
7条回答
  • 2020-12-18 18:29

    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

    0 讨论(0)
  • 2020-12-18 18:29

    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.

    0 讨论(0)
  • 2020-12-18 18:29

    try using char(13) + char(10) instead of '\n' in your string (define a constant and concatenate to your sql)

    0 讨论(0)
  • 2020-12-18 18:30

    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;
    
    0 讨论(0)
  • 2020-12-18 18:30

    Another simple solution is to click the "results to text" button in SSMS. Its not super clean, but gives you visibility to line breaks with about half a second of work.

    0 讨论(0)
  • 2020-12-18 18:38

    I echo David C's answer, except you should use the "TYPE" keyword so that you can click to open the data in a new window.

    Note that any unsafe XML characters will not work well with either of our solutions.

    Here is a proof of concept:

    DECLARE @ErrorLog TABLE (ErrorText varchar(500), ErrorDate datetime);
    INSERT INTO @ErrorLog (ErrorText, ErrorDate) VALUES
        ('This is a long string with a' + CHAR(13) + CHAR(10) + 'line break.', getdate()-1),
        ('Another long string with' + CHAR(13) + CHAR(10) + '<another!> line break.', getdate()-2);
    SELECT
        (
            SELECT  ErrorText AS '*'
            FOR XML PATH(''), TYPE
        ) AS 'ErrorText',
        ErrorDate
    FROM        @ErrorLog
    ORDER BY    ErrorDate;
    

    I can confirm that the line breaks are preserved when copying out of a grid in SSMS 2012.

    0 讨论(0)
提交回复
热议问题