Trim spaces in string - LTRIM RTRIM not working

后端 未结 8 1791
你的背包
你的背包 2021-02-03 19:14

I tried this code -

UPDATE Table
SET Name = RTRIM(LTRIM(Name))

Data type of Name is varchar(25)

None of the leading and t

8条回答
  •  执笔经年
    2021-02-03 20:09

    It is a frequent occurrence that we must remove leading and trailing whitespaces from a string before additional processing or sending it to another layer in an application. We can’t always control how the data is entered. The data might come from another system, a data conversion, an old application, EDI, Excel, or from an application which had poor quality control. In some of those cases, a whitespace might not be entered or saved in the system as character 32 which is a whitespace entered in a keyboard. If that happens, SQL built in functions for trimming whitespaces do not work so it becomes necessary to replace the “other” whitespace characters with character 32. Then LTRIM and RTRIM will work as expected.

    **Select [udfTrim](ColumnName) from Table**
    
    **CREATE FUNCTION [dbo].[udfTrim] 
    (
        @StringToClean as varchar(8000)
    )**
    RETURNS varchar(8000)
    AS
    BEGIN   
        --Replace all non printing whitespace characers with Characer 32 whitespace
        --NULL
        Set @StringToClean = Replace(@StringToClean,CHAR(0),CHAR(32));
        --Horizontal Tab
        Set @StringToClean = Replace(@StringToClean,CHAR(9),CHAR(32));
        --Line Feed
        Set @StringToClean = Replace(@StringToClean,CHAR(10),CHAR(32));
        --Vertical Tab
        Set @StringToClean = Replace(@StringToClean,CHAR(11),CHAR(32));
        --Form Feed
        Set @StringToClean = Replace(@StringToClean,CHAR(12),CHAR(32));
        --Carriage Return
        Set @StringToClean = Replace(@StringToClean,CHAR(13),CHAR(32));
        --Column Break
        Set @StringToClean = Replace(@StringToClean,CHAR(14),CHAR(32));
        --Non-breaking space
        Set @StringToClean = Replace(@StringToClean,CHAR(160),CHAR(32));
    
        Set @StringToClean = LTRIM(RTRIM(@StringToClean));
        Return @StringToClean
    END
    

提交回复
热议问题