I have a table where a int column should either be set to zero or to a value which does not already exist in the table. Can I prevent inserting non zerod duplicated values in such column with a CHECK CONSTRAINT or should I use a BEFORE INSERT trigger? in case I could do this with both, what design is better?
From the .NET windows forms application we are using a global transaction scope to wrap the save and in both cases I would like the insert to fail and the transaction to roll back completely so I don’t know if I should put the rollback inside the trigger, that’s why I would rather try with a check if possible.
Database: SQL 2008
Thanks.
See the link in Andriy M’s comment, it mention a 2008 new concept : filtered index…
CREATE UNIQUE INDEX indexName ON tableName(columns) INCLUDE includeColumns WHERE columnName != 0This will create an index of unique items that are not 0.
Any attempt to insert a duplicate non-zero value will breach the uniqueness of the index and cause an error.