views:

51

answers:

1

There is a need to build constraint on the column that guarantees that only one value in all rows is 1 and all the others are 0.

Solution with triggers exists but I would like to have something built in.

Is such thing possible at all?

+6  A: 

Edit

Actually I just noticed you are on SQL Server 2008 you could use a filtered index for this

CREATE UNIQUE NONCLUSTERED INDEX UIX ON YourTable (col) where col = 1

Original Answer

The easiest way would probably be to store this one special pk in a separate one row table. The no more than one row aspect can be enforced with check constraints.

CREATE TABLE OneRowTable
(
lock CHAR(1) DEFAULT 'X' NOT NULL PRIMARY KEY CHECK (lock = 'X'),
OtherTablePK int
);

Otherwise assuming you might have an id field comprised of positive integers you could add a computed column with the following definition

case when col=1 then -1 else id end

and add a unique constraint to that.

Martin Smith
@Tim - No. Using UDFs in check constraints can fail with multi row updates and under snapshot isolation. I'd just use the filtered index approach. It will ensure that at most 1 row can contain the value `1`. If you update your question with your table definition I'll try and clarify my second suggestion. (Edit: That was in reply to your earlier comment that seems to have gone now!)
Martin Smith
@Martin, yeah, I have checked that in details and it became clear. Thanks!
Tim