Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 use rtrim function for all columns and save this modification into this existing table?

Edit: is there a way to do it using stored procedure or cursor where I don't have to manually declare all columns?

like image 777
atricapilla Avatar asked Mar 31 '10 10:03

atricapilla


2 Answers

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 :)

like image 174
AdaTheDev Avatar answered Sep 17 '22 09:09

AdaTheDev


UPDATE xxx
  SET col1 = RTRIM(col1),
      col2 = RTRIM(col2),
      col3 = RTRIM(col3),
      ...
like image 27
Marcelo Cantos Avatar answered Sep 17 '22 09:09

Marcelo Cantos