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

问题描述 投票:0回答:11

我没有看到任何关于这个主题的类似问题,我必须为我现在正在做的事情进行研究。我想我会发布答案,以防其他人有同样的问题。

sql sql-server line-breaks
11个回答
733
投票

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

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

344
投票

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

您只需连接字符串并在想要换行的位置插入

CHAR(13)
即可。

示例:

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

这会打印出以下内容:

这是1号线。
这是2号线。


106
投票

另一种方法是这样的:

INSERT CRLF SELECT 'fox 
jumped'

也就是说,只需在编写查询时在查询中插入换行符,就会将类似的换行符添加到数据库中。这适用于 SQL Server Management studio 和查询分析器。我相信如果您在字符串上使用 @ 符号,这也适用于 C#。

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

59
投票

所有这些选项的工作原理取决于您的情况,但是 如果您使用 SSMS,您可能看不到其中任何一个工作(正如一些评论中提到的 SSMS 隐藏 CR/LF)

因此,与其自己开车绕弯,请检查

中的此设置

Tools
|
Options


36
投票

在 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','`','
')

18
投票

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

替换占位符来完成

好问题,我自己从来没有做过:)


13
投票

我来到这里是因为我担心我在 C# 字符串中指定的 cr-lfs 没有显示在 SQl Server Management Studio 查询响应中。

事实证明,它们在那里,但没有被显示。

要“查看”cr-lfs,请使用如下打印语句:

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

11
投票

我会说

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

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

5
投票

这是一个 C# 函数,它将文本行添加到现有文本 blob 中,以 CRLF 分隔,并返回适合

INSERT
UPDATE
操作的 T-SQL 表达式。它有一些我们专有的错误处理,但是一旦你把它撕掉,它可能会有所帮助 - 我希望如此。

/// <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
投票

这总是很酷,因为当您从 Oracle 等导出列表时,您会获得跨越多行的记录,这反过来对于 cvs 文件等可能很有趣,所以要小心。

无论如何,Rob的答案很好,但我建议使用@以外的东西,多尝试一些,比如§§@@§§之类的,这样它就有机会获得一些独特性。 (但是,请记住您要插入的

varchar
/
nvarchar
字段的长度..)


1
投票

在某些特殊情况下,您可能会发现这很有用(例如在 MS 报告中渲染单元格内容)
示例:

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

该语句传递的不是一个包含 CR\LF 的字符串,而是一个包含一列(名为 [Copy_and_execute_this_statement] )和三行的小表。这可能适合消费者,他们吞下 CR\LF 但可以消费表(例如 MS Report)另一个简单的例子是

select * from ( values ( 'Adam'),('Eva')) as t([some_name])

© www.soinside.com 2019 - 2024. All rights reserved.