Skip to content

Instantly share code, notes, and snippets.

@josephbales
Last active September 19, 2016 18:49
Show Gist options
  • Save josephbales/943a94c042727cd59371313f1a5901e6 to your computer and use it in GitHub Desktop.
Save josephbales/943a94c042727cd59371313f1a5901e6 to your computer and use it in GitHub Desktop.
Trim all columns in a database T-SQL
-- Replace <DATABASE> with the name of your database
-- May also need to change the DATA_TYPE inside the cursor to fit your schema
DECLARE @TABLENAME NVARCHAR(255)
DECLARE @SQL NVARCHAR(MAX)
DECLARE db_cursor CURSOR FOR
SELECT TABLE_NAME
FROM <DATABASE>.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @TABLENAME
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = NULL
SELECT @SQL = COALESCE(@SQL + ',[', '[') +
COLUMN_NAME + ']=RTRIM(LTRIM([' + COLUMN_NAME + ']))'
FROM <DATABASE>.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TABLENAME
AND DATA_TYPE IN ('nvarchar', 'varchar')
SET @SQL = 'UPDATE [' + @TABLENAME + '] SET ' + @SQL
EXECUTE (@SQL)
FETCH NEXT FROM db_cursor INTO @TABLENAME
END
CLOSE db_cursor
DEALLOCATE db_cursor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment