I have a table that looks like this:
ClientId FloorNum BedNum IsActive
11 2 212 1
12 2 214 0
12 2 214 1
13 2 215 0
13 2 215 0
13 2 215 0
13 2 215 0
13 2 215 1
12 2 215 1
As you can see, FloorNum/BedNum combination 2/215 has two rows where IsActive equals 1. This cannot happen.
On the other hand, one FloorNum/BedNum combination can have many rows where IsActive equals 0.
How can I add a constraint to a table so that a FloorNum/BedNum combination can only have one row where IsActive = 1?
Any help is appreciated.
Primary Key will prevent the entry of duplicate rows.
In the Navigation Pane, right-click the table that contains the field, and then click Design View. Select the field that you want to make sure has unique values. In the Field Properties pane at the bottom of the table design view, on the General tab, set the Indexed property to Yes (No duplicates).
A unique constraint (also referred to as a unique key constraint) is a rule that forbids duplicate values in one or more columns within a table. Unique and primary keys are the supported unique constraints.
You can create a filtered unique index with a WHERE clause.
CREATE UNIQUE NONCLUSTERED INDEX IX_[index name]_FloorNum_BedNum ON [myTable] (
FloorNum ASC,
BedNum ASC)
WHERE (IsActive = 1)
This will only take into account records where the IsActive
column is set to 1
.
Based on your description I think that ClientId
is not necessary in this example but if I am wrong you can add it to the index as well.
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