SQL Server TRIM character

前端 未结 17 2162
感情败类
感情败类 2020-12-09 17:11

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

17条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 17:41

    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..

提交回复
热议问题