SQL Server TRIM character

Nate Pet picture Nate Pet · Oct 20, 2011 · Viewed 98.8k times · Source

I have the following string: 'BOB*', how do I trim the * so it shows up as 'BOB'

I tried the RTRIM('BOB*','*') but does not work as says needs only 1 parameter.

Answer

Teejay picture Teejay · Feb 1, 2013

Another pretty good way to implement Oracle's TRIM char FROM string in MS SQL Server is the following:

  • First, you need to identify a char that will never be used in your string, for example ~
  • You replace all spaces with that character
  • You replace the character * you want to trim with a space
  • You LTrim + RTrim the obtained string
  • You replace back all spaces with the trimmed character *
  • You replace back all never-used characters with a space

For example:

REPLACE(REPLACE(LTrim(RTrim(REPLACE(REPLACE(string,' ','~'),'*',' '))),' ','*'),'~',' ')