2011-01-25 72 views
3

我正在使用SQL Server。我想将一个名为[DateCreated]的列添加到多个表中。是否有可能通过单个语句将此列添加到数据库中的所有表中?是否可以同时将列添加到多个表中?

我偶然发现了Joe Steffaneli的一个答案,他在这个答案中提出了一个查询,该查询又返回包含Alter table语句的行。 查询如下:

select 'alter table ' + quotename(s.name) + '.' + quotename(t.name) + ' add [DateModified] datetime' 
    from sys.columns c 
     inner join sys.tables t 
      on c.object_id = t.object_id 
     inner join sys.schemas s 
      on t.schema_id = s.schema_id 
     left join sys.columns c2 
      on t.object_id = c2.object_id 
       and c2.name = 'DateModified' 
    where c.name = 'DateCreated' 
     and t.type = 'U' 
     and c2.column_id is null /* DateModified column does not already exist */ 

有没有办法,我可以执行返回的行什么办法?对不起英文。

+3

国家的DBMS您使用,我们可以给你一个批处理语句来实现相同的。 – RichardTheKiwi 2011-01-25 08:39:12

+0

我正在使用SQL Server。 – Bhaskar 2011-01-25 09:04:40

回答

5

你可能需要这样的东西。检查脚本在运行之前是否做了你想要的(添加一个非空列,默认值为getdate())!

DECLARE @Dynsql nvarchar(max) 
SET @Dynsql = '' 

SELECT @Dynsql = @Dynsql + ' 
alter table ' + QUOTENAME(SCHEMA_NAME(schema_id))+ '.' + QUOTENAME(name) + 
' add [DateCreated] datetime not null default getdate()' 
FROM sys.tables 
WHERE type='U' and object_id NOT IN (select object_id from sys.columns where name='DateCreated') 


EXEC (@Dynsql) 
-1

不,没有单个语句会将列添加到数据库中的所有表中。

下一次请使用您正在使用的RDBMS标记您的问题。如果有办法,我们将无法在不知道您正在使用哪种数据库系统的情况下提供命令。

1

此存储过程工作正常

USE databaseName; 
exec sp_msforeachtable 'alter table ? Add [DateCreated] datetime not null default getdate()'; 
0
declare @i int 

set @i=1 
while(@i<45) 
begin 
    declare @sql varchar(200) 

    with TempTable as (select Row_number() over(order by stdID) as RowNo,* from SomeTable) 

    select @sql= 'alter table Table'+(select Name from TempTable where [email protected])+' add NewColumn int' 

    exec (@sql) 
    set @[email protected]+1 
end 
相关问题