如果存在则添加外键

时间:2016-11-10 16:53:18

标签: mysql sql innodb

我想从1个表

创建一个外键
CREATE TABLE IF NOT EXISTS PEs (id INT(20) AUTO_INCREMENT PRIMARY KEY, Name varchar(20), Message varchar(30), CoordsX double(9,6) SIGNED, CoordsY double(9,6) SIGNED, CoordsZ double(9,6) SIGNED, Status smallint(1) DEFAULT 1, world varchar(20))

到第二个表

CREATE TABLE IF NOT EXISTS`rh_pe`.`attributes` ( `toid` INT(20) NOT NULL , `Kommentar` VARCHAR(60) NOT NULL , `Aktion` varchar(10) NOT NULL , `Person1` INT NOT NULL , `Person2` INT  ) ENGINE = InnoDB;

外键应如下:

ALTER TABLE `attributes` ADD  CONSTRAINT `Const` FOREIGN KEY (`toid`) REFERENCES `pes`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT;

我试过

IF NOT EXISTS(ALTER TABLE `attributes` ADD  CONSTRAINT `Const` FOREIGN KEY (`toid`) REFERENCES `pes`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT);

ALTER TABLE `attributes` ADD  CONSTRAINT `Const` FOREIGN KEY IF NOT EXISTS (`toid`) REFERENCES `pes`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT

1 个答案:

答案 0 :(得分:0)

你的两个表示例都有相同的名称,所以我在你的约束示例中提到你的第二个表名是“pes”。这应该工作:

IF NOT EXISTS (SELECT * FROM sys.objects o WHERE o.object_id = object_id(N'`rh_pe`.`Const`') AND OBJECTPROPERTY(o.object_id, N'IsForeignKey') = 1)
BEGIN
    ALTER TABLE `rh_pe`.`attributes` ADD  CONSTRAINT `Const` FOREIGN KEY (`toid`) REFERENCES `rh_pe`.`pes`(`id`) ON DELETE RESTRICT ON UPDATE RESTRICT;
END

我没有使用“if(not)exists”的句子,但你可以在这里找到类似的问题:If Foreign Key Not Exist Then Add Foreign Key Constraint(Or Drop a Foreign Key Constraint If Exist) without using Name?