Thursday, September 5, 2013

TSQL - Count number of lines in string

Counting \r\n in a TSQL string and determine the number of new lines.
DECLARE @str VARCHAR(128) SET @str = RTRIM(LTRIM( 'Line 1' + CHAR(13)+CHAR(10) + 'Line 2' + CHAR(13)+CHAR(10) + 'Line 3' + CHAR(13)+CHAR(10) + 'Line 4' )) SELECT @str , (LEN(@str) - LEN(REPLACE(@str, CHAR(13)+CHAR(10), ''))) / 2 + IIF( CHARINDEX(CHAR(10)+CHAR(13), REVERSE(@str), 0) = 1, 0, 1) AS strNoOfLines

Share/Bookmark

No comments: