all groups > sql server programming > october 2003 >
You're in the

sql server programming

group:

Foreign Key OR 0


Foreign Key OR 0 Michael Carr
10/29/2003 11:34:10 PM
sql server programming: I'd like to set up a constraint on a field such that it must be either zero
or equal to a foreign key. Is there a way to do this in SQL Server?

Thanks!
Michael Carr

Re: Foreign Key OR 0 Louis Davidson
10/30/2003 10:35:18 AM
Why? You could use null for this, but null really signifies that you will
possibly maybe have a value, just it isn't set yet.

Instead of having a zero pointing at nothing, create a foreign key value
that says 'None' with a value of 0. Now you are telling users of this data
that no way do you expect to have a different value of this key.

--
----------------------------------------------------------------------------
-----------
Louis Davidson (drsql@hotmail.com)
Compass Technology Management

Pro SQL Server 2000 Database Design
http://www.apress.com/book/bookDisplay.html?bID=266

Note: Please reply to the newsgroups only unless you are
interested in consulting services. All other replies will be ignored :)

[quoted text, click to view]

Re: Foreign Key OR 0 Andrew Pozolotin
10/30/2003 11:10:30 AM
Michael,
you can use NULL or PRIMARY KEY value

Example -

create table test (
a int primary key,
b varchar(10)
)
go

create table test2(
c int references test(a),
d varchar(10)
)
go

insert into test values (1, 'a')
insert into test values (2, 'b')
insert into test values (3, 'c')
insert into test values (4, 'd')

insert into test2 values (1, 'd')
insert into test2 values (null, 'r')
insert into test2 values (10, 'r') -- ERROR

drop table test
drop table test2

Andrew

[quoted text, click to view]

Re: Foreign Key OR 0 Michael Carr
11/5/2003 11:37:57 PM
One drawback with your solution is that you can't simultaneously enforce
constraint "0 or TableA" on Table B and constraint "TableA" on Table C. With
the NULL solution, this becomes possible because you can simply allow or
disallow NULL values on the child tables.

Michael Carr

[quoted text, click to view]

Re: Foreign Key OR 0 Louis Davidson
11/6/2003 12:00:48 AM
True, but it would be just as easy to enforce this in a check constraint
that says value <> 0.

--
----------------------------------------------------------------------------
-----------
Louis Davidson (drsql@hotmail.com)
Compass Technology Management

Pro SQL Server 2000 Database Design
http://www.apress.com/book/bookDisplay.html?bID=266

Note: Please reply to the newsgroups only unless you are
interested in consulting services. All other replies will be ignored :)

[quoted text, click to view]

AddThis Social Bookmark Button