简体   繁体   English

将列值限制为0或在插入时唯一

[英]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. 我有一个表,其中int列应设置为零或表中尚不存在的值。 Can I prevent inserting non zerod duplicated values in such column with a CHECK CONSTRAINT or should I use a BEFORE INSERT trigger? 我可以使用CHECK CONSTRAINT阻止在此类列中插入非零重复值,还是应该使用BEFORE INSERT触发器? 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. 从.NET Windows窗体应用程序我们使用全局事务范围来包装保存,在这两种情况下我都希望插入失败并且事务完全回滚,所以我不知道是否应该将回滚放入触发器,这就是为什么我宁愿尝试检查,如果可能的话。

Database: SQL 2008 数据库:SQL 2008

Thanks. 谢谢。

See the link in Andriy M's comment, it mention a 2008 new concept : filtered index... 请参阅Andriy M评论中的链接,它提到了2008年的新概念:过滤指数...

CREATE UNIQUE INDEX indexName ON tableName(columns) INCLUDE includeColumns WHERE columnName != 0

This will create an index of unique items that are not 0. 这将创建不为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.? 为什么你使用零而不是null。 If you had it as null then the db would handle it for you easily via a nullable unique constraint.. 如果你把它作为null,那么db会通过一个可以为空的唯一约束轻松地为你处理它。

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. 如果你可以满足0为NULL的需求,你可以使用一个唯一约束,但无论如何,提供答案都是触发器的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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