How to trim a string in SQL Server before 2017?

后端 未结 7 1560
心在旅途
心在旅途 2020-12-04 17:25

In SQL Server 2017, you can use this syntax, but not in earlier versions:

SELECT Name = TRIM(Name) FROM dbo.Customer;
7条回答
  •  無奈伤痛
    2020-12-04 17:53

    I assume this is a one-off data scrubbing exercise. Once done, ensure you add database constraints to prevent bad data in the future e.g.

    ALTER TABLE Customer ADD
       CONSTRAINT customer_names__whitespace
          CHECK (
                 Names NOT LIKE ' %'
                 AND Names NOT LIKE '% '
                 AND Names NOT LIKE '%  %'
                );
    

    Also consider disallowing other characters (tab, carriage return, line feed, etc) that may cause problems.

    It may also be a good time to split those Names into family_name, first_name, etc :)

提交回复
热议问题