Rico (yo*@me.com) writes:
I have a foreign key constraint between two tables (Appointments and
MissedAppointme ntReasons) and I'd like to allow null values in
Appointments table for the field containing the MissedAppointme ntReason,
but currently, I get a Foreign Key Constraint Error when I try to add a
record to the Appointments table.
Then you are writing a value to MissedAppointRe ason that does exist
in that table, for instance 0.
That is, NULL values do not cause FK violation. Try this:
CREATE TABLE first (a int NOT NULL,
CONSTRAINT pk_first PRIMARY KEY(a))
CREATE TABLE second (b int NOT NULL,
a int NULL,
CONSTRAINT pk_second PRIMARY KEY(b),
CONSTRAINT fk FOREIGN KEY (a) REFERENCES first(a))
go
INSERT first (a) VALUES (1)
go
INSERT second (b, a) VALUES( 1, 1) -- goes fine.
INSERT second (b, a) VALUES( 2, NULL) -- goes fine.
INSERT second (b, a) VALUES( 3, 2) -- error.
go
SELECT * FROM second
go
DROP TABLE second, first
--
Erland Sommarskog, SQL Server MVP,
es****@sommarsk og.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx