简体   繁体   中英

How can I reference multiple foreign key in one table to a single primary key in ms sql

I tried this query and it doesn't work. Says that I must use ON DELETE NO ACTION, but I need to set null for deleted references

CREATE TABLE airports
(
    id integer primary key identity(1,1),
    country varchar(50) not null,
    city varchar(50) not null,
    airport_name varchar(50) not null,
    airport_class varchar(50) not null
);

CREATE TABLE flights
(
    id integer primary key identity(1,1),
    code integer unique not null,
    departure_point integer,
    arrival_point integer,
    departure_time datetime not null,
    arrival_time datetime not null,
    foreign key(departure_point) references airports(id) on delete set null,
    foreign key(arrival_point) references airports(id) on delete set null
);

The error (it's in russian, sorry)

Введение ограничения внешнего ключа (FOREIGN KEY) "FK__flights__arrival__286302EC" для таблицы "flights" может привести к появлению циклов или множественных каскадных путей. Укажите ON DELETE NO ACTION или ON UPDATE NO ACTION либо измените другие ограничения внешнего ключа (FOREIGN KEY). 

This is a bit long for a comment.

I don't think this is possible in SQL Server. Unfortunately, SQL Server only allows one set null per foreign table reference.

That said, you might have other options:

  • I'm not sure that having flights with NULL airports is actually useful. You might want to delete the entire row.
  • If you liked, you could stash the flight information in an archive table, with NULL values or invalid foreign key references.
  • You can soft delete the airports. Just have a flag for whether the airport is active.

It works if I create separate tables with two columns: one is primary and a foreign key references a flight, and another is regular foreign key references an airport.

Here is my database diagram:

数据库图

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