Sample Header Ad - 728x90

Trim Trailing Whitespace, Tab, Newline, Carriage Returns, etc

5 votes
5 answers
16215 views
I am working with SQL Server 2008 and I am looking for a function like ltrim and rtrim which will also remove leading and trailing tabs, double spaces, carriage returns, line feeds, etc. There are a number of functions out there but the ones I found all have limitations, e.g. truncate the string to 8000 characters. e.g. (according to some of the comments): SQL SERVER – 2008 – Enhenced TRIM() Function – Remove Trailing Spaces, Leading Spaces, White Space, Tabs, Carriage Returns, Line Feeds One of the comments proposed a better solution but the - 1 causes an incorrect syntax error and I am not sure why. CREATE FUNCTION dbo.SuperTrimLeft(@str varchar(MAX)) RETURNS varchar(MAX) AS BEGIN IF (ASCII(LEFT(@str, 1)) < 33) BEGIN SET @str = STUFF(@str, 1, PATINDEX('%[^'+CHAR(0)+'-'+CHAR(32)+']%', @str) – 1, ' '); END; RETURN @str; END; So my question is, what is the best approach to accomplish the task above?
Asked by GWR (2847 rep)
May 2, 2016, 12:12 PM
Last activity: Mar 28, 2025, 12:09 PM