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 paramet
Trim with many cases
--id = 100 101 102 103 104 105 106 107 108 109 110 111
select right(id,2)+1 from ordertbl -- 1 2 3 4 5 6 7 8 9 10 11 -- last two positions are taken
select LEFT('BOB', LEN('BOB')-1) -- BO
select LEFT('BOB*',1) --B
select LEFT('BOB*',2) --BO
Another pretty good way to implement Oracle's TRIM char FROM string
in MS SQL Server is the following:
~
*
you want to trim with a spaceLTrim
+ RTrim
the obtained string*
For example:
REPLACE(REPLACE(LTrim(RTrim(REPLACE(REPLACE(string,' ','~'),'*',' '))),' ','*'),'~',' ')
How about.. (in this case to trim off trailing comma or period)
For a variable:
-- Trim commas and full stops from end of City
WHILE RIGHT(@CITY, 1) IN (',', '.'))
SET @CITY = LEFT(@CITY, LEN(@CITY)-1)
For table values:
-- Trim commas and full stops from end of City
WHILE EXISTS (SELECT 1 FROM [sap_out_address] WHERE RIGHT([CITY], 1) IN (',', '.'))
UPDATE [sap_out_address]
SET [CITY] = LEFT([CITY], LEN([CITY])-1)
WHERE RIGHT([CITY], 1) IN (',', '.')
RRIM() LTRIM() only remove spaces try http://msdn.microsoft.com/en-us/library/ms186862.aspx
Basically just replace the * with empty space
REPLACE('TextWithCharacterToReplace','CharacterToReplace','CharacterToReplaceWith')
So you want
REPLACE ('BOB*','*','')
Solution for one char parameter:
rtrim('0000100','0') -> select left('0000100',len(rtrim(replace('0000100','0',' '))))
ltrim('0000100','0') -> select right('0000100',len(replace(ltrim(replace('0000100','0',' ')),' ','.')))
I really like Teejay's answer, and almost stopped there. It's clever, but I got the "almost too clever" feeling, as, somehow, your string at some point will actually have a ~
(or whatever) in it on purpose. So that's not defensive enough for me to put into production.
I like Chris' too, but the PATINDEX
call seems like overkill.
Though it's probably a micro-optimization, here's one without PATINDEX
:
CREATE FUNCTION dbo.TRIMMIT(@stringToTrim NVARCHAR(MAX), @charToTrim NCHAR(1))
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @retVal NVARCHAR(MAX)
SET @retVal = @stringToTrim
WHILE 1 = charindex(@charToTrim, reverse(@retVal))
SET @retVal = SUBSTRING(@retVal,0,LEN(@retVal))
WHILE 1 = charindex(@charToTrim, @retVal)
SET @retVal = SUBSTRING(@retVal,2,LEN(@retVal))
RETURN @retVal
END
--select dbo.TRIMMIT('\\trim\asdfds\\\', '\')
--trim\asdfds
Returning a MAX
nvarchar bugs me a little, but that's the most flexible way to do this..