Remove all spaces from a string in SQL Server

后端 未结 23 849
死守一世寂寞
死守一世寂寞 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:10

    Reference taken from this blog:

    First, Create sample table and data:

    CREATE TABLE tbl_RemoveExtraSpaces
    (
         Rno INT
         ,Name VARCHAR(100)
    )
    GO
    
    INSERT INTO tbl_RemoveExtraSpaces VALUES (1,'I    am     Anvesh   Patel')
    INSERT INTO tbl_RemoveExtraSpaces VALUES (2,'Database   Research and     Development  ')
    INSERT INTO tbl_RemoveExtraSpaces VALUES (3,'Database    Administrator     ')
    INSERT INTO tbl_RemoveExtraSpaces VALUES (4,'Learning    BIGDATA    and       NOSQL ')
    GO
    

    Script to SELECT string without Extra Spaces:

    SELECT
         [Rno]
        ,[Name] AS StringWithSpace
        ,LTRIM(RTRIM(REPLACE(REPLACE(REPLACE([Name],CHAR(32),'()'),')(',''),'()',CHAR(32)))) AS StringWithoutSpace
    FROM tbl_RemoveExtraSpaces
    

    Result:

    Rno         StringWithSpace                                 StringWithoutSpace
    ----------- -----------------------------------------  ---------------------------------------------
    1           I    am     Anvesh   Patel                      I am Anvesh Patel
    2           Database   Research and     Development         Database Research and Development
    3           Database    Administrator                       Database Administrator
    4           Learning    BIGDATA    and       NOSQL          Learning BIGDATA and NOSQL
    

提交回复
热议问题