简体   繁体   中英

SQL Alter Table Foreign key On Delete

I have a table in my database called trains with these columns:

id , name , station .

Station is the foreign key to other table stations . When I delete some specific row from stations , since trains references to this table, I get an error. 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:

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).

If you are using SQL Server, then you cannot alter a foreign key constraint to add on delete. 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;

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