是否可以同时将列添加到多个表中?

Bha*_*kar 6 sql-server alter-table

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

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

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 */ 
Run Code Online (Sandbox Code Playgroud)

有什么办法可以执行返回的行吗?对不起英文.

Mar*_*ith 9

你可能需要这样的东西.在运行脚本之前检查脚本是否符合要求(添加一个非空列,默认值为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)
Run Code Online (Sandbox Code Playgroud)