简体   繁体   中英

Transact SQL: how to create double sided foreign key constraints?

Say I have two tables: A and B

A has one column which is a primary key on B , ie, a foreign key and B has one column which is a primary key on A , ie, a foreign key.

So I would do

CREATE TABLE A(
 idA INT PRIMARY KEY,
 idB INT FOREIGN KEY REFERENCES B(idB)
);

CREATE TABLE B(
 idB INT PRIMARY KEY,
 idA INT FOREIGN KEY REFERENCES A(idA)
);

and would expect it to work; however, the sql server management studio gives me the following error: Foreign key references invalid table for table B If I swap their order, the error will be in the table A instead.

How do I overcome this issue, given that I have a double sided relationships, ie, A references B and B references A .

You have to do the first constraint with a separate ALTER TABLE , because the reference table has not yet been defined. SQL has no concept of a "forward reference" in this case.

CREATE TABLE A (
 idA INT PRIMARY KEY,
 idB INT
);

CREATE TABLE B (
 idB INT PRIMARY KEY,
 idA INT FOREIGN KEY REFERENCES A(idA)

);

ALTER TABLE A
    ADD CONSTRAINT FK_A_B FOREIGN KEY (idB) REFERENCES B(idB);

Some database designers have the habit of doing all foreign key constraints after the table definitions so they don't have to worry about the order the table definitions.

They usually arrive at this pattern after adding a new foreign key somewhere and watching a script fail because of the ordering of the table declarations.

Here is a db<>fiddle.

So, I see people are going to answer this without asking the obvious question:

Why the circular reference?

Perhaps there is some brilliant design I am missing, but the idea you FK a PK on one table and then do the converse seems like REALLY bad design. I am open to learning, but it sounds like a disaster.

In general:

  • With one-to-many, one table is a parent, or lookup, and the other has an FK to that table
  • With one-to-one, you normally dupe the ID (subclass) so there can be only one in each table. Or, you redesign and create a single table.
  • You can constrain, via other means, but you still have a circular concept in your schema

Your abstract "here is what I am doing" is not real world enough for me to suggest a better way of achieving your actual business goal, rather than simply telling you how to do something I see will likely be a train wreck one day.

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