I have found this useful when importing certain text files into a staging table prior to appending main tables, and when it is typical that many of the imported text columns are padded with leading or trailing spaces.Naturally, this can also be handled in VBScript processes during DTS as part of the import steps...but still...this comes in handy at times.Passing a table name to the proc builds an Update statment to update the table char/varchar/nvarchar/nchar type columns with a trim statement.Not sure if it can be done without a cursor..but it is effectiveWorks in both 2000/2005It is most beneficial for leading spaces and for the char type column.SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO CREATE Proc [dbo].[pTrimCharacterFields](@TableName varchar(100))AsDECLARE @SQLstring varchar(8000)DECLARE @firstTime bit -- Start building our UPDATE statementSELECT @SQLstring = 'UPDATE ' + @TableName +' SET 'SELECT @firstTime = 1 -- Get a list of character columns in this tableDECLARE getColumnsCursor CURSORREAD_ONLYFORSELECT c.COLUMN_NAMEFROM INFORMATION_SCHEMA.COLUMNS cWHERE c.TABLE_SCHEMA = 'dbo' AND c.TABLE_NAME = @TableName AND c.DATA_TYPE IN ('char', 'nchar', 'varchar', 'nvarchar')ORDER BY c.COLUMN_NAME DECLARE @columnName nvarchar(128)OPEN getColumnsCursor FETCH NEXT FROM getColumnsCursor INTO @columnNameWHILE (@@FETCH_STATUS <> -1)BEGIN IF (@@FETCH_STATUS <> -2) BEGIN IF (@firstTime = 0) SELECT @SQLstring = @SQLstring + ',' -- append our column to the UPDATE statement SELECT @SQLstring = @SQLstring + '[' + @columnName + ']=LTRIM(RTRIM([' + @columnName + ']))' SELECT @firstTime = 0 END FETCH NEXT FROM getColumnsCursor INTO @columnNameEND CLOSE getColumnsCursorDEALLOCATE getColumnsCursor EXEC(@SQLstring)GO SET ANSI_NULLS OFFGOSET QUOTED_IDENTIFIER OFFGO
Here is a test of it.Create Table TrimTest (ColumnA char(10) not null, ColumnB nvarchar(10) not null, ColumnC varchar(10) not null, ColumnD nchar(10) not null)Insert Into TrimTest(ColumnA,ColumnB,ColumnC, ColumnD)Select ' TestA ', ' Test B ', ' TestC ', 'A 1 'Select ColumnA,Len(ColumnA) as LenA, ColumnB, Len(ColumnB) as LenB, ColumnC,len(ColumnC) as LenC, ColumnD,len(ColumnD) as LenDFROM TrimTestExec dbo.pTrimCharacterFields 'TrimTest'Select ColumnA,Len(ColumnA) as LenA, ColumnB, Len(ColumnB) as LenB, ColumnC,len(ColumnC) as LenC, ColumnD,len(ColumnD) as LenDFROM TrimTestDrop Table TrimTest
Poor planning on your part does not constitute an emergency on my part.