开发者

SQL iterate over information_schema.columns

I have a SQL Server table with 100 columns. I would like to do this to each column:

UPDATE 2011INFODATA
SET [Attribute_Code_1] = ltrim(rtrim(Attribute_Code_1))
WHERE len(ltrim(rtrim(Attribute_Code_1))) > 0

My q开发者_如何学Gouestion is how I can use the informatin_schema.columns to dynamically generate or insert the various column names into the above SQL?

I could of course do it by hand for each column and get the same result. But that would be no fun and I want to use this same sql for many tables.


Something along these lines will do it.

DECLARE @Sql nvarchar(max)
SET @Sql = '';
SELECT @Sql = @Sql + '
    UPDATE 2011INFODATA
    SET ' + QUOTENAME(COLUMN_NAME) + ' = ltrim(rtrim(' + QUOTENAME(COLUMN_NAME) + '))
    WHERE len(ltrim(rtrim(' + QUOTENAME(COLUMN_NAME) + '))) > 0'
FROM information_schema.columns
WHERE TABLE_NAME = '2011INFODATA' AND DATA_TYPE LIKE '%char'
EXEC sp_executesql @Sql

Edit: updated sample SQL to incorporate helpful comments from @billinkc, @Martin Smith, @Aaron Bertrand.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜