sql-将列(外键到表之一)添加到数据库中的所有表

时间:2018-12-31 08:48:27

标签: sql sql-server

我正在尝试向db中的所有表添加新列,这是该表之一的外键。理想情况下,我应该将列添加到所有表中,而不是外键引用的表中。

如何将这两个SQL语句合并为一个语句?

// 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);

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

请检查

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';

答案 1 :(得分:0)

您可以使用以下查询生成您的alter语句,然后复制粘贴并在以下脚本中执行。

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';