简体   繁体   中英

sql - Add column(foreign key to one of the table) to all tables in databases

I am trying to add a new column to all tables in db which is a foreign key to one of the table. Ideally I should add the column to all tables instead of the table that the foreign key reference to.

How do I combine these two SQL statements to only one statement?

// Get all tables except the foreign key reference to
SELECT * 
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="arthurMurray"
AND TABLE_TYPE="BASE TABLE"
AND TABLE_NAME!="Competitions";

// Add compeition_id to table as a foreign key to competitions table
ALTER TABLE t
ADD competition_id INTEGER,
ADD CONSTRAINT FOREIGN KEY(competition_id) REFERENCES Competitions(id);

Any help will be appreciate!

Please check this

EXEC sp_MSforeachtable '
if not exists (select * from sys.columns 
               where object_id = object_id(''?'')
               and name = ''CreatedOn'') 
begin
    ALTER TABLE ? ADD CreatedOn datetime NOT NULL DEFAULT getdate();
end';

you ca use below query to generate your alter statement then you ca copy paste and execute below script.

SELECT 
  'ALTER TABLE ' +  TABLE_NAME + 'ADD competition_id INTEGER,  ADD CONSTRAINT FOREIGN KEY(competition_id) REFERENCES Competitions(id);'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA='whatever_schema'
  AND TABLE_TYPE='BASE TABLE'
  AND TABLE_NAME!='Competitions';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM