Last active
September 19, 2016 18:49
-
-
Save josephbales/943a94c042727cd59371313f1a5901e6 to your computer and use it in GitHub Desktop.
Trim all columns in a database T-SQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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