Remove Trailing Spaces and Update in Columns in SQL Server

前端 未结 13 1052
抹茶落季
抹茶落季 2020-12-22 20:42

I have trailing spaces in a column in a SQL Server table called Company Name.

All data in this column has trailing spaces.

I want to remove all

相关标签:
13条回答
  • 2020-12-22 20:57

    Try SELECT LTRIM(RTRIM('Amit Tech Corp '))

    LTRIM - removes any leading spaces from left side of string

    RTRIM - removes any spaces from right

    Ex:

    update table set CompanyName = LTRIM(RTRIM(CompanyName))
    
    0 讨论(0)
  • 2020-12-22 21:02

    Example:

    SELECT TRIM('   Sample   ');
    

    Result: 'Sample'

    UPDATE TableName SET ColumnName = TRIM(ColumnName)
    
    0 讨论(0)
  • 2020-12-22 21:06
    SELECT TRIM(ColumnName) FROM dual;
    
    0 讨论(0)
  • 2020-12-22 21:08

    If we also want to handle white spaces and unwanted tabs-

    Check and Try the below script (Unit Tested)-

    --Declaring
    DECLARE @Tbl TABLE(col_1 VARCHAR(100));
    
    --Test Samples
    INSERT INTO @Tbl (col_1)
    VALUES
    ('  EY     y            
    Salem')
    , ('  EY     P    ort       Chennai   ')
    , ('  EY     Old           Park   ')
    , ('  EY   ')
    , ('  EY   ')
    ,(''),(null),('d                           
        f');
    
    SELECT col_1 AS INPUT,
        LTRIM(RTRIM(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
            REPLACE(
            REPLACE(
            REPLACE(
            REPLACE(
            REPLACE(
            REPLACE(col_1,CHAR(10),' ')
            ,CHAR(11),' ')
            ,CHAR(12),' ')
            ,CHAR(13),' ')
            ,CHAR(14),' ')
            ,CHAR(160),' ')
            ,CHAR(13)+CHAR(10),' ')
        ,CHAR(9),' ')
        ,' ',CHAR(17)+CHAR(18))
        ,CHAR(18)+CHAR(17),'')
        ,CHAR(17)+CHAR(18),' ')
        )) AS [OUTPUT]
    FROM @Tbl;
    
    0 讨论(0)
  • 2020-12-22 21:09

    If you are using SQL Server (starting with vNext) or Azure SQL Database then you can use the below query.

    SELECT TRIM(ColumnName) from TableName;
    

    For other SQL SERVER Database you can use the below query.

    SELECT LTRIM(RTRIM(ColumnName)) from TableName
    

    LTRIM - Removes spaces from the left

    example: select LTRIM(' test ') as trim = 'test '

    RTRIM - Removes spaces from the right

    example: select RTRIM(' test ') as trim = ' test'

    0 讨论(0)
  • 2020-12-22 21:10

    Well, it depends on which version of SQL Server you are using.

    In SQL Server 2008 r2, 2012 And 2014 you can simply use TRIM(CompanyName)

    SQL Server TRIM Function

    In other versions you have to use set CompanyName = LTRIM(RTRIM(CompanyName))

    0 讨论(0)
提交回复
热议问题