Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove only leading or trailing carriage returns

I'm dumbfounded that this question has not been asked meaningfully already. How does one go about creating an equivalent function in SQL like LTRIM or RTRIM for carriage returns and line feeds ONLY at the start or end of a string.

Obviously REPLACE(REPLACE(@MyString,char(10),''),char(13),'') removes ALL carriage returns and new line feeds. Which is NOT what I'm looking for. I just want to remove leading or trailing ones.

like image 368
dynamphorous Avatar asked Jun 24 '15 19:06

dynamphorous


People also ask

How do I remove a carriage return in SQL?

In the Find box hold down the Alt key and type 0 1 0 for the line feed and Alt 0 1 3 for the carriage return. They can now be replaced with whatever you want.

What are trailing spaces in SQL?

When the right side of a LIKE predicate expression features a value with a trailing space, SQL Server does not pad the two values to the same length before the comparison occurs.


1 Answers

Find the first character that is not CHAR(13) or CHAR(10) and subtract its position from the string's length.

LTRIM()

SELECT RIGHT(@MyString,LEN(@MyString)-PATINDEX('%[^'+CHAR(13)+CHAR(10)+']%',@MyString)+1) 

RTRIM()

SELECT LEFT(@MyString,LEN(@MyString)-PATINDEX('%[^'+CHAR(13)+CHAR(10)+']%',REVERSE(@MyString))+1) 
like image 135
Anon Avatar answered Oct 14 '22 13:10

Anon