Programming

SQL Server VARCHAR / NVARCHAR 문자열에 줄 바꿈을 삽입하는 방법

procodes 2020. 2. 11. 22:45
반응형

SQL Server VARCHAR / NVARCHAR 문자열에 줄 바꿈을 삽입하는 방법


나는이 주제에 관해 비슷한 질문을 보지 못했고, 지금 연구하고있는 것에 대해 연구해야했습니다. 다른 사람이 같은 질문을 할 경우를 대비하여 답변을 게시하겠다고 생각했습니다.


char(13)입니다 CR. DOS / Windows 스타일 줄 CRLF바꿈의 경우 다음 char(13)+char(10)과 같이 원합니다 .

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

나는 여기서 대답을 찾았습니다 : http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in- 암호/

문자열을 연결하고 CHAR(13)줄 바꿈을 원하는 곳에 삽입 하십시오.

예:

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

이것은 다음을 인쇄합니다.

이것은 1
행입니다. 2 행입니다.


이를 수행하는 다른 방법은 다음과 같습니다.

INSERT CRLF SELECT 'fox 
jumped'

즉, 쿼리 중에 줄 바꿈을 삽입하면 데이터베이스에 유사한 줄 바꿈이 추가됩니다. 이것은 SQL Server Management Studio 및 Query Analyzer에서 작동합니다. @ 기호를 문자열로 사용하면 C #에서도 작동한다고 생각합니다.

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

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

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) 로 바꿔서 수행 할 수있는 것 같습니다.

좋은 질문입니다.


C # 문자열에 지정한 cr-lf가 SQl Server Management Studio 쿼리 응답에 표시되지 않을까 걱정했기 때문에 여기에 도착했습니다.

그것들이 있지만 표시되지 않습니다.

cr-lf를 "보려면"다음과 같은 print 문을 사용하십시오.

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

다음은 C #을 기능입니다 그 앞에 추가 텍스트있는 CRLF로 구분 기존 텍스트 덩어리에 라인, 반환에 적합한 T-SQL 식 INSERT또는 UPDATE작업. 그것은 우리의 독점적 인 오류 처리를 가지고 있지만 일단 그것을 제거하면 도움이 될 수 있습니다.

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

나는 말할 것이다

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

또는

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

오라클과 같이 목록을 내보낼 때 레코드가 여러 줄에 걸쳐 있기 때문에 cvs 파일과 같이 흥미로울 수 있으므로 항상주의해야합니다.

어쨌든 Rob의 대답은 좋지만 @ 이외의 다른 것을 사용하는 것이 좋습니다 .§§ @@ §§ 또는 다른 것과 같은 몇 가지를 시도해보십시오. 따라서 독창성이 될 수 있습니다. (그러나 여전히 삽입 하려는 varchar/ nvarchar필드 의 길이를 기억하십시오 ..)

참고 : https://stackoverflow.com/questions/31057/how-to-insert-a-line-break-in-a-sql-server-varchar-nvarchar-string



반응형