简体   繁体   中英

How to Trim leading and trailing tab spaces in MSSQL query

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.

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));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM