How could I set a constraint on a table so that only one of the records has its isDefault
bit field set to 1?
The constraint is not table scope, but one default per set of rows, specified by a FormID.
Constraints can be assigned on a column or table level. Column level constraints apply only to one column, while table level constraints can apply to multiple columns or the whole table.
The DEFAULT constraint is used to set a default value for a column. The default value will be added to all new records, if no other value is specified.
A primary key constraint uniquely identifies each row/record in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values.
On SQL Server 2008 or higher you can simply use a unique filtered index
CREATE UNIQUE INDEX IX_TableName_FormID_isDefault ON TableName(FormID) WHERE isDefault = 1
Where the table is
CREATE TABLE TableName( FormID INT NOT NULL, isDefault BIT NOT NULL )
For example if you try to insert many rows with the same FormID
and isDefault
set to 1 you will have this error:
Cannot insert duplicate key row in object 'dbo.TableName' with unique index 'IX_TableName_FormID_isDefault'. The duplicate key value is (1).
Source: http://technet.microsoft.com/en-us/library/cc280372.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With