A non-archived barcode must only appear once in the table.
All archived barcodes do not need to be unique
My table has these columns
- ID int (generated by database)
- Barcode nvarchar(50)
- Archived bit
Sample data
ID |Barcode |Archived
-----|-----------|--------
1 |AB1234US | 0
2 |AB1234US | 0 <-- NOT allowed, this is a duplicate and not archived
3 |AB1234US | 1 <-- yes allowed, this is archived
4 |AB1234US | 1 <-- ditto
5 |CD6789JP | 0
6 |EF9012YE | 0
7 |EF9012YE | 1 <-- allowed
What I've tried.
I've added a composite key made up of the barcode and the archived flag. But this will not allowed more than one archived barcode.
ALTER TABLE [Parcels] ADD CONSTRAINT [Barcode_Archived] UNIQUE
NONCLUSTERED
(
[Barcode] ASC,
[Archived] ASC
Question How to force uniqueness for non-archived barcodes but not for archived barcodes?