Skip to content

Instantly share code, notes, and snippets.

@kevindb
Last active August 29, 2015 14:18
Show Gist options
  • Save kevindb/0c7310f5a65d97f8f871 to your computer and use it in GitHub Desktop.
Save kevindb/0c7310f5a65d97f8f871 to your computer and use it in GitHub Desktop.
Trims leading and trailing whitespace from every column in a SQL Server table
SET NOCOUNT ON;
DECLARE @TABLE VARCHAR(100),
@SQL VARCHAR(MAX);
SET @TABLE = '';
SELECT @SQL = COALESCE(@SQL, '')
+ CAST( 'UPDATE ' + @TABLE + ' ' +
'SET [' + C.COLUMN_NAME + '] = LTRIM(RTRIM(' + C.COLUMN_NAME + ')) ' +
'WHERE ([' + C.COLUMN_NAME + '] LIKE '' %'' ' +
'OR [' + C.COLUMN_NAME + '] LIKE ''% ''); ' + Char(13)
AS VARCHAR(MAX))
FROM INFORMATION_SCHEMA.COLUMNS C
JOIN sysobjects B
ON C.TABLE_NAME = B.NAME
WHERE C.TABLE_NAME = @TABLE
AND C.DATA_TYPE = 'varchar'
AND B.xtype = 'U';
EXEC(@SQL);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment