Adding a column to all user tables in t-sql

2019-01-27 14:34发布

问题:

I need to add a delete flag column to all 40 user tables in a database. I could write a script to loop through sys.tables, but I thought I'd check and see if anyone has either a better solution, or pre-created sql for this scenario.

回答1:

There is an undocumented but well known stored procedure sp_msforeachtable:

exec sp_msforeachtable 'alter table ? add flag bit not null default 0';


回答2:

No, it's a manual loop.

Or you could build up a single SQL statement of course...

SELECT 
    'ALTER TABLE ' + T.name + ' ADD foo int NULL'
FROM
    sys.tables AS T
WHERE
    T.is_ms_shipped = 0

Or the undocumented

EXEC sys.sp_MSforeachtable 'ALTER TABLE ? ADD foo int NULL'