Tuesday, November 27, 2012

REMOVE TAB, NEW LINE AND RETURN CARRIAGE FROM STRING (T-SQL)


I've been facing this issue for many years now and it came back again this morning. Actually, here is presented a problem dealing with character field that consist of mysterious "hidden" blank spaces.
Also, this might cause some troubles in while copying data and bringing it over to some other applications like MS Excel.

Well, here is the whole investigation and the solution that I've been using:




DECLARE @testString varchar(255)
set @testString = 'MY STRING      '
 /*Select the string and try to copy and paste into notepad and tab is still there*/
SELECT testString = @testString

/*Ok, it seems easy, let's try to trim this. Huh, it doesn't work, the same result here.*/
SELECT testStringTrim = RTRIM(@testString)

/*Let's try to get the size*/
SELECT LenOfTestString = LEN(@testString)

/*This supposed to give us string together with blank space, but not for tab though*/
SELECT DataLengthOfString= DATALENGTH(@testString)

SELECT ASCIIOfTab = ASCII(' ')
SELECT CHAR(9)

/*I always use this like a final solution*/
SET @testString = REPLACE(REPLACE(REPLACE(@testString, CHAR(9), ''), CHAR(10), ''), CHAR(13), '') SELECT @testString  

/*
CHAR(9)       - Tab
CHAR(10) - New Line
CHAR(13) - Carriage Return
*/



Mike C.



 

7 comments:

  1. thanks .. works for me...

    ReplyDelete
  2. Your final solution works but while concatenating new line to old one it removes space between last word of first line & first word of other line.

    Example: line1
    line2 = line1line2


    ReplyDelete
  3. bookmarked your blog. you're doing a great job

    ReplyDelete
  4. Following removes multiple tabs with one space:
    SELECT REPLACE(REPLACE(REPLACE('STRING WITH MULTIPLE TABS',CHAR(9),CHAR(7) + ' '), ' '+CHAR(7), ''), CHAR(7), '')

    Thanks.

    ReplyDelete
  5. Great job
    Works for me.

    ReplyDelete
  6. Amazing, it totally worked!

    ReplyDelete
  7. Thanks Mladen. Very handy code!

    ReplyDelete