简体   繁体   中英

Limit column value to 0 or to be unique on insert

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 != 0

This 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.

why are you using zero instead of null.? If you had it as null then the db would handle it for you easily via a nullable unique constraint..

Check constraint, when used properly, prevent bad data. They do not change the bad data to good. For that reason, I would aim for a trigger instead. If you can get around the need for a 0 as NULL, you could use a unique constraint, but supplying the answer would be the job of a trigger regardless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM