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
LEFT('BOB*', LEN('BOB*')-1)
should do it.
CREATE FUNCTION dbo.TrimCharacter
(
@Value NVARCHAR(4000),
@CharacterToTrim NVARCHAR(1)
)
RETURNS NVARCHAR(4000)
AS
BEGIN
SET @Value = LTRIM(RTRIM(@Value))
SET @Value = REVERSE(SUBSTRING(@Value, PATINDEX('%[^'+@CharacterToTrim+']%', @Value), LEN(@Value)))
SET @Value = REVERSE(SUBSTRING(@Value, PATINDEX('%[^'+@CharacterToTrim+']%', @Value), LEN(@Value)))
RETURN @Value
END
GO
--- Example
----- SELECT dbo.TrimCharacter('***BOB*********', '*')
----- returns 'BOB'
If you wanted behavior similar to how RTRIM handles spaces i.e. that "B*O*B**" would turn into "B*O*B" without losing the embedded ones then something like -
REVERSE(SUBSTRING(REVERSE('B*O*B**'), PATINDEX('%[^*]%',REVERSE('B*O*B**')), LEN('B*O*B**') - PATINDEX('%[^*]%', REVERSE('B*O*B**')) + 1))
Should do it.
@teejay solution is great. But the code below can be more understandable:
declare @X nvarchar(max)='BOB *'
set @X=replace(@X,' ','^')
set @X=replace(@X,'*',' ')
set @X= ltrim(rtrim(@X))
set @X=replace(@X,'^',' ')
SqlServer2017 has a new way to do it: https://docs.microsoft.com/en-us/sql/t-sql/functions/trim-transact-sql?view=sql-server-2017
SELECT TRIM('0' FROM '00001900'); -> 19
SELECT TRIM( '.,! ' FROM '# test .'); -> # test
SELECT TRIM('*' FROM 'BOB*'); --> BOB
Unfortunately, RTRIM does not support trimming a specific character.
SELECT REPLACE('BOB*', '*', '')
SELECT REPLACE('B*OB*', '*', '')
-------------------------------------
Result : BOB
-------------------------------------
this will replace all asterisk* from the text