简体   繁体   中英

Complex Foreign Key Constraint in SQL

Is there a way to define a constraint using SQL Server 2005 to not only ensure a foreign key exists in another table, but also meets a certain criteria?

For example, say I have two tables:

Table A
--------
Id - int
FK_BId - int

Table B
--------
Id - int
Name - string
SomeBoolean - bit

Can I define a constraint that sayd FK_BId must point to a record in Table B, AND that record in Table B must have SomeBoolean = true? Thanks in advance for any help you can provide.

You can enforce the business rule using a composite key on (Id, SomeBoolean) , reference this in table A with a CHECK constraint on FK_BSomeBoolean to ensure it is always TRUE. BTW I'd recommend avoiding BIT and instead using CHAR(1) with domain checking eg

CHECK (SomeBoolean IN ('F', 'T'))

The table structure could look like this:

CREATE TABLE B
(
 Id INTEGER NOT NULL UNIQUE, -- candidate key 1
 Name VARCHAR(20) NOT NULL UNIQUE,  -- candidate key 2
 SomeBoolean CHAR(1) DEFAULT 'F' NOT NULL
    CHECK (SomeBoolean IN ('F', 'T')), 
 UNIQUE (Id, SomeBoolean) -- superkey
); 

CREATE TABLE A 
(
 Ib INTEGER NOT NULL UNIQUE, 
 FK_BId CHAR(1) NOT NULL, 
 FK_BSomeBoolean CHAR(1) DEFAULT 'T' NOT NULL
    CHECK (FK_BSomeBoolean = 'T')
 FOREIGN KEY (FK_BId, FK_BSomeBoolean)
    REFERENCES B (Id, SomeBoolean)
);

I think what you're looking for is out of the scope of foreign keys, but you could do the check in triggers, stored procedures, or your code.

If it is possible to do, I'd say that you would make it a compound foreign key, using ID and SomeBoolean , but I don't think it actually cares what the value is.

In some databases (I can't check SQL Server) you can add a check constraint that references other tables.

ALTER TABLE a ADD CONSTRAINT fancy_fk
CHECK (FK_BId IN (SELECT Id FROM b WHERE SomeBoolean));

I don't believe this behavior is standard.

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