SQL Server: How to perform Rtrim on all varchar columns of a table

前端 未结 5 1959
眼角桃花
眼角桃花 2020-12-30 01:40

I have over 30 columns in my table (sql server 2008). Columns type are varchar(x). I know that in every column there is two extra spaces at the end of column value. How to u

相关标签:
5条回答
  • 2020-12-30 01:47

    For a generic approach, you can use a script like this to generate the statement for you, for a given table (useful if you have many columns!):

    DECLARE @SQL VARCHAR(MAX)
    DECLARE @TableName NVARCHAR(128)
    SET @TableName = 'YourTableName'
    
    SELECT @SQL = COALESCE(@SQL + ',[', '[') + 
                  COLUMN_NAME + ']=RTRIM([' + COLUMN_NAME + '])'
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = @TableName
        AND DATA_TYPE = 'varchar'
    
    SET @SQL = 'UPDATE [' + @TableName + '] SET ' + @SQL
    PRINT @SQL
    

    That will just print the SQL statement out. You can either then copy + run the statement, or just EXECUTE(@SQL). This is untested, so just try it out on a test table first :)

    0 讨论(0)
  • 2020-12-30 01:48
    UPDATE xxx
      SET col1 = RTRIM(col1),
          col2 = RTRIM(col2),
          col3 = RTRIM(col3),
          ...
    
    0 讨论(0)
  • 2020-12-30 01:59

    The accepted answer works well. I ran into an issue with a temp table being named the same name. You can add

    and TABLE_SCHEMA = 'dbo'
    

    And that will get rid of collision on table names.

    0 讨论(0)
  • 2020-12-30 02:05

    It is perfect... But remember to put also the where clause:

    COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA+'.'+TABLE_NAME),COLUMN_NAME,'IsComputed') = 0

    Ohterwise you will get an error if the table has a computed column of "%char%" type!

    0 讨论(0)
  • 2020-12-30 02:06

    We can have stored procedure to trim specific table under specific schema. If we have different schema names other than default dbo schema, it is better to use this SP by passing schema name and table name. This performs both LTRIM and RTRIM. This SP would check char, nchar, varchar, nvarchar columns.

    CREATE PROCEDURE [dbo].[TrimAllColumnsOfTable] @SchemaName Varchar(100),@TableName Varchar(100)
    AS
    BEGIN
    
    DECLARE @SQL VARCHAR(MAX)
    SELECT @SQL = COALESCE(@SQL + ',[', '[') +
                  COLUMN_NAME + ']=LTRIM(RTRIM([' + COLUMN_NAME + ']))'
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = @SchemaName AND TABLE_NAME = @TableName AND DATA_TYPE Like '%char%'
    
    SET @SQL = 'UPDATE [' + @SchemaName + '].[' + @TableName + '] SET ' + @SQL
    
    EXEC (@SQL)
    
    END
    

    USAGE: [TrimAllColumnsOfTable] 'SchemaName','TableName'

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