13
votes

I have data which has leading and trailing spaces in the string. when storing that data in database I want to trim the space in query itself before storing into DB.

Normal spaces are trimming properly with RTRIM and LTRIM function but if a string contains tab space,its not trimming the tab space from the input string.

Can anyone help me to get the string with trimmed with tab space from leading and trailing.

2
replace all tabs with spaces, trim the intermediate string, then convert spaces back to tabs?Marc B

2 Answers

16
votes

Replace the ASCII code for tab (9):

replace(@str, char(9), '')

To only remove the outer tabs, first change them to something that won't exist in your data (I use a series of four spaces in this example), then rtrim/ltrim, then convert that same sequence back to tabs:

replace(ltrim(rtrim(replace(@str, char(9), '    '))),'    ', char(9));
0
votes

Try this:

DECLARE @InputString nvarchar(50) = CHAR(9) + CHAR(9) + ' 123'+ 'abc ' + CHAR(9);
SELECT @InputString AS InputString
      ,REVERSE(RIGHT(REVERSE(RIGHT(@InputString, LEN(@InputString) - PATINDEX('%[^'+CHAR(9)+']%', @InputString) + 1)), LEN(REVERSE(RIGHT(@InputString, LEN(@InputString) - PATINDEX('%[^'+CHAR(9)+']%', @InputString) + 1))) - PATINDEX('%[^'+CHAR(9)+']%', REVERSE(RIGHT(@InputString, LEN(@InputString) - PATINDEX('%[^'+CHAR(9)+']%', @InputString) + 1))) + 1)) AS OutputString
;

Maybe you should refactor it as a function. Note, it may works only above Sql Server 2008. You can replace CHAR(9) to any character you like to trim.