[英]SQL Alter Table Foreign key On Delete
I have a table in my database called trains with these columns:我的数据库中有一个名为 trains 的表,其中包含以下列:
id
, name
, station
. id
号、 name
、 station
。
Station is the foreign key to other table stations
.站是其他表stations
的外键。 When I delete some specific row from stations
, since trains
references to this table, I get an error.当我从stations
中删除某些特定行时,由于trains
引用了该表,因此出现错误。 Hence, what I try to do is to do alter table
on trains
and add on delete set null
attribute to station
column, like this:因此,我尝试做的是在trains
上执行alter table
并将on delete set null
属性添加到station
列,如下所示:
alter table trains alter column station on delete set null;
However, this seems to be the wrong syntax and I can't find the right one, which can make this without removing the whole table and creating it again (so I need to use this alter
command).但是,这似乎是错误的语法,我找不到正确的语法,这样就可以在不删除整个表并再次创建它的情况下做到这一点(所以我需要使用这个alter
命令)。
If you are using SQL Server, then you cannot alter a foreign key constraint to add on delete.如果您使用的是 SQL 服务器,则无法更改外键约束以添加删除。 First drop the constraint and then create a new one.首先删除约束,然后创建一个新约束。
ALTER TABLE trains
DROP CONSTRAINT constraintname;
ALTER TABLE trains
ADD CONSTRAINT fk_station
FOREIGN KEY (child_column_name)
REFERENCES stations(parent_column_name)
ON DELETE CASCADE;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.