Is it possible to add a column to multiple tables at the same time?

I am using SQL Server. I want to add a single column named [DateCreated] to multiple tables. Is it possible that with a single statement I could add this column to all the tables in my database?

I stumble upon Joe Steffaneli's answer, in which he suggested a query that, in turn, returns rows containing Alter table instructions. The request is as follows:

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 */ 

Is there a way I can execute returned strings? Sorry for the english.

+3
source share
4 answers

, , . , script , , ( 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)
+5

USE databaseName;
exec sp_msforeachtable 'alter table ? Add [DateCreated] datetime not null default getdate()';
+1
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 RowNo=@i)+' add NewColumn int'

    exec (@sql)
    set @i=@i+1
end
0
source

No, there is no single statement that will add a column to all tables in your database.

Next time mark your question with the RDBMS you are using. If there was a way, we would not be able to give you a command without knowing which database system you are using.

-1
source

Source: https://habr.com/ru/post/1787633/


All Articles