You are here: Re: SS 2005 Express- Allowing null values and Foriegn Key Constraints « MsSQL Server « IT news, forums, messages
Re: SS 2005 Express- Allowing null values and Foriegn Key Constraints

Posted by Erland Sommarskog on 12/28/06 22:38

Rico (you@me.com) writes:
> I have a foreign key constraint between two tables (Appointments and
> MissedAppointmentReasons) and I'd like to allow null values in
> Appointments table for the field containing the MissedAppointmentReason,
> 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 MissedAppointReason 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, esquel@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация