如何在SQL Server VARCHAR / NVARCHAR字符串中插入换行符

我没有看到关于这个主题的任何相似的问题,我不得不研究这个我如今正在作的事情。 觉得我会发布答案,以防其余人有一样的问题。 sql


#1楼

我来到这里是由于我担忧我在C#字符串中指定的cr-lfs没有在SQl Server Management Studio查询响应中显示。 数据库

事实证实,他们在那里,但没有被展现。 express

要“看到”cr-lfs,请使用以下的print语句: app

declare @tmp varchar(500)    
select @tmp = msgbody from emailssentlog where id=6769;
print @tmp

#2楼

这是一个C#函数,它将文本行预先添加到由CRLF分隔的现有文本blob,并返回适合INSERTUPDATE操做的T-SQL表达式。 它有一些咱们专有的错误处理,可是一旦你扯掉它,它可能会有所帮助 - 我但愿如此。 curl

/// <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("");
    }
}

#3楼

我在这里找到了答案: http//blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-码/ ide

您只需链接字符串并在您想要换行的位置插入CHAR(13)函数

例: 网站

DECLARE @text NVARCHAR(100)
SET @text = 'This is line 1.' + CHAR(13) + 'This is line 2.'
SELECT @text

这打印出如下内容: ui

这是第1行。
这是第2行。 this


#4楼

关注Google ...

从网站上获取代码:

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))

看起来能够经过用CHAR替换占位符来完成(13)

好问题,历来没有本身作过:)


#5楼

char(13)CR 。 对于DOS- / Windows风格的CRLF换行符,您须要char(13)+char(10) ,如:

'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'

#6楼

这老是很酷,由于当您从Oracle获取导出列表时,您会得到跨越多行的记录,这反过来可能对cvs文件感兴趣,因此要当心。

不管如何,Rob的答案很好,可是我建议使用除了@以外的其余东西,再尝试一些,好比§§@@§§或其余东西,这样它就有机会得到一些独特性。 (可是,请记住您要插入的varchar / nvarchar字段的长度..)


#7楼

在SSMS中运行它,它显示了SQL自己的换行符如何成为跨越行的字符串值的一部分:

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))

结果:
第1行
第2行
第3行

空白行有多长时间了?
2

什么是ASCII值?
13
10

或者,若是你想在一行(几乎!)上指定你的字符串,你能够使用这样的REPLACE() (可选择使用CHAR(13)+CHAR(10)做为替换):

PRINT REPLACE('Line 1`Line 2`Line 3','`','
')

#8楼

我会说

concat('This is line 1.', 0xd0a, 'This is line 2.')

要么

concat(N'This is line 1.', 0xd000a, N'This is line 2.')

#9楼

另外一种方法是这样的:

INSERT CRLF SELECT 'fox 
jumped'

也就是说,只需在编写查询时在查询中插入换行符,就会向数据库中添加相似的中断。 这适用于SQL Server Management Studio和Query Analyzer。 我相信若是你在字符串上使用@符号,这也适用于C#。

string str = @"INSERT CRLF SELECT 'fox 
    jumped'"