对许多表执行alter

时间:2011-08-22 08:56:16

标签: tsql sql-server-2008

我有很多表,名称以Lookup_开头。如何在每个这样的表中更改列Name

2 个答案:

答案 0 :(得分:3)

我不太确定你想用Name做什么,但这是你把它改成nvarchar(20)的方法。

Declare @sql as nvarchar(500)
Declare TableCursor CURSOR FAST_FORWARD FOR
SELECT 'alter table ' + table_schema + '.'+ table_name +' alter column name nvarchar(20)' FROM INFORMATION_SCHEMA.TABLES
WHERE left(table_name, 7) = 'lookup_' and table_type = 'BASE TABLE'

OPEN TableCursor
FETCH NEXT FROM TableCursor
INTO @sql
WHILE @@FETCH_STATUS = 0
BEGIN
     EXEC (@sql)
     FETCH NEXT FROM TableCursor
     INTO @sql
END
CLOSE TableCursor
DEALLOCATE TableCursor

答案 1 :(得分:1)

这看起来好多了

exec sp_msforeachtable 
    @command1 = 'alter table ? alter column name nvarchar(20)'
    , @whereand = 'and left(o.name, 7) = ''lookup_'' and o.type = ''U'''