Remove Newline Tab Character in Data using SQL Server

While working on an application, I came across a small column with some Newline and Tab characters in it. The requirement was to replace these characters. Here’s how to remove/replace the Newline characters in your data. I will demonstrate this example with a string, but you can easily replace it with a column name

DECLARE @str as nvarchar(70)
SET @str = 'APPT 5212
NORTH BLOCK, 7th Av
MUMBAI,MAH'

SELECT @str AS 'Orginal String'

DECLARE @CrLf CHAR(2);
SET @CrLf = CHAR(13) + CHAR(10); -- CarriageReturn + LineFeed

SELECT
REPLACE(REPLACE(SUBSTRING(@str,1,DATALENGTH(@str)),@CrLf,'-'), CHAR(9), '')
AS 'String with No Newlines or TABS'

The CHAR() string function converts an ascii code to character and can be used to insert control characters into strings. Over here we are using three types of control character

CHAR(9) - Tab

CHAR(10) – LineFeed

Char(13) - CarriageReturn

A newline or line break is CHAR(13) + CHAR(10). In the code shown above, we look for all Newline and Tab characters and replace it with a ‘-‘ and ‘’ respectively.

OUTPUT

image

1 comment:

  1. For Oracle databases, one can make use of REPLACE function as follows -
    REPLACE(Con.COMMENTS, CHR(13) || CHR(10), ‘ ‘) as “Updated_Comments”



    For a detailed example, please refer to following link:
    http://crackingsiebel.wordpress.com/2010/08/21/oracle-sql-replace-newline-or-linefeed-character/

    ReplyDelete