This is a bit of a hack, but if you have a primary key/unique constraint on an identity column, you can add a computed column with a CASE expression and then put a unique constraint on it, like so:create table #a (i int not null identity(1,1), uid int not null, status tinyint not null,consCol as case when status=1 then cast(uid as varchar) + '_' + cast(status as varchar) elsecast(i as varchar) end,constraint PK_#a primary key(i),constraint unq_consCol unique(consCol))insert #a(uid, status) select 1,1insert #a(uid, status) select 2,1insert #a(uid, status) select 3,1insert #a(uid, status) select 1,2insert #a(uid, status) select 1,2insert #a(uid, status) select 1,2insert #a(uid, status) select 1,2select * from #ainsert #a(uid, status) select 1,1 --this will failselect * from #a
SQL Server doesn't support CHECK constraints that perform SELECTs. You could create a user-defined function that does a SELECT on the table and return a value if it finds a dupe, but you will incur a LOT of disk activity if you do multi-row INSERT or UPDATE operations. You could also do something similar in a trigger, but again you'll incur excess I/O.The downside of using the constraint on the computed column is disk space used to maintain the unique index, but otherwise this is the method I would use. You just need to modify it to use your column names.