views:

47

answers:

4

I have a following table, Client.

create table Client (
    ClientID    int identity primary key,
    TaxID       varchar(12),
    SSN         varchar(12)
)
GO

Client can have either TaxID or SSN or both. But either one should exist.
Currently, I am enforcing the rule thru following trigger.

create trigger trgClient_UniqueTaxIDSSN
    on Client
    after Insert, Update
as
    --; Check if either TaxID or SSN is not null.

But is there a way to declare a constraint to enforce the rule?

+1  A: 

You should be able to create a Check Constraint, on the Client table, to do this.

http://msdn.microsoft.com/en-us/library/ms188258.aspx
Randy Minder
+1  A: 

A CHECK constraint that checks for null with a boolean OR would seem to do the trick.

jlew
+5  A: 
ALTER TABLE Client ADD CONSTRAINT ck_TaxIDorSSN CHECK 
    (TaxID is not null or SSN is not null)
Adam Robinson
+1 for giving code not links. Oh, and being correct :-)
gbn
@Adam: Thanks Adam. I was playing around with creating a check constraint in-line within `CREATE TABLE`. I wasn't aware of declaring a `CHECK` constraint thru `ALTER TABLE`. Right now I was creating a function to pass to CHECK constraint, which was kind of fruitless.
Sung Meister
+1  A: 

You can create a Check constraint that checks for null in either field:

ALTER TABLE Client ADD CONSTRAINT cn_TaxIDorSSNnotNULL CHECK 
  (TaxID IS NOT NULL OR SSN IS NOT NULL)
Oded