Wednesday, December 12, 2007

Using SQL to iterate through all the columns in a table

I use this code in ETL projects where almost all of the columns need to be cleaned, and it is easier to execte the same SQL code over all the columns in all the imported tables, rather than write custom code for each column in the ETL package (SSIS in my case).

declare @TableName as varchar(2000)
declare @ColName as varchar(2000)
declare @Sql as nvarchar(4000)

declare curColNames cursor for
select distinct
'[' + C.TABLE_SCHEMA + '].[' + C.TABLE_NAME + ']' as TableName
,'[' + C.COLUMN_NAME + ']' as ColName
from
INFORMATION_SCHEMA.COLUMNS C
join INFORMATION_SCHEMA.TABLES T
on C.TABLE_SCHEMA = T.TABLE_SCHEMA
and C.TABLE_NAME = T.TABLE_NAME
where
T.TABLE_TYPE = 'BASE TABLE'
order by
TableName
,ColName


open curColNames

fetch next from curColNames
into @TableName, @ColName

WHILE @@FETCH_STATUS = 0
BEGIN
set @Sql = 'update ' + @TableName + ' set ' + @ColName + '= ltrim(rtrim(' + @ColName + '))'

exec sp_executesql @Sql

fetch next from curColNames
into @TableName, @ColName
end

close curColNames
deallocate curColNames