Remove all spaces from a string in SQL Server

后端 未结 23 912
死守一世寂寞
死守一世寂寞 2020-11-28 01:42

What is the best way to remove all spaces from a string in SQL Server 2008?

LTRIM(RTRIM(\' a b \')) would remove all spaces at the right and left of th

23条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 02:09

    For some reason, the replace works only with one string each time. I had a string like this "Test           MSP" and I want to leave only one space.

    I used the approach that @Farhan did, but with some modifications:

    CREATE FUNCTION ReplaceAll
    (
        @OriginalString varchar(8000),
        @StringToRemove varchar(20),
        @StringToPutInPlace varchar(20)
    )
    RETURNS varchar(8000)
    AS
    BEGIN
    declare @ResultStr varchar(8000)
    set @ResultStr = @OriginalString
    while charindex(@StringToRemove, @ResultStr) > 0
        set @ResultStr = replace(@ResultStr, @StringToRemove, @StringToPutInPlace)
    
    return @ResultStr
    END
    

    Then I run my update like this

    UPDATE tbTest SET Description = dbo.ReplaceAll(Description, '  ', ' ') WHERE ID = 14225
    

    Then I got this result: Test MSP

    Posting here if in case someone needs it as I did.

    Running on: Microsoft SQL Server 2016 (SP2)

提交回复
热议问题