问题
I have a SQL Server table with two columns id:INT and flagged:BOOLEAN. Is it possible to add a constraint that ensures that there is only one entry for (id=a, flagged=b) where b = 1?
For example:
ok
(id=1, flagged=1)
(id=1, flagged=0)
(id=1, flagged=0)
not ok
(id=1, flagged=1)
(id=1, flagged=1)
(id=1, flagged=0)
回答1:
Create Unique Index with filter:
CREATE UNIQUE INDEX idx_name ON your_table(id)
WHERE flagged=1;
Demo:
SqlFiddleDemo
CREATE TABLE your_table(id INT, flagged INT);
CREATE UNIQUE INDEX idx_name ON your_table(id)
WHERE flagged=1;
INSERT INTO your_table(id, flagged)
VALUES (1, 0), (1,1), (1,0);
INSERT INTO your_table(id, flagged) -- will fail
VALUES (1,1);
/* Cannot insert duplicate key row in object 'dbo.your_table'
with unique index 'idx_name'. The duplicate key value is (1).*/
来源:https://stackoverflow.com/questions/32473877/partial-value-constraint-of-sql-server-table