唯一约束与预检查
我使用 SQL Server 2008,并且有一个包含 varchar(X) 类型列的表,我希望该表具有唯一值。
实现这一目标的最佳方法是什么?我应该使用唯一约束并捕获异常,还是应该在插入新值之前进行预检查?
一个问题是,该应用程序被许多用户使用,因此我猜测预检查可能会导致竞争条件,以防两个用户插入相同的值。
谢谢
I use SQL Server 2008, and I have a table with a column of type varchar(X) which I want to have unique values.
What is the best way to achieve that? Should I use unique constraint and catch an exception, or should I pre-check before inserting a new value?
One issue, the application is used by many users so I guess that pre-checking might result in race condition, in case that two users will insert the same values.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
竞争条件是一个需要注意的极好点。
为什么不两者都做呢? - 预先检查,以便您可以向用户提供良好的反馈,但绝对有唯一的约束作为您的最终保障。
Race condition is an excellent point to be aware of.
Why not do both? - pre-check so you can give good feedback to the user, but definitely have the unique constraint as your ultimate safeguard.
让数据库为您完成工作。创建唯一约束。
Let the DB do the work for you. Create the unique constraint.
如果要求值是唯一的——那么约束是实现这一点的唯一有保证的方法。可靠的所谓预检查将需要一定程度的锁定,这将使系统的该部分本质上是单用户。
If it's a requirement that the values be unique --- then a constraint is the only guaranteed way to achieve that. reliable so-called pre-checking will require a level of locking that will make that part of your system essentially single user.
使用约束(UNIQUE 或 PRIMARY KEY)。这样,每个应用程序都会强制执行密钥。如果需要,您可以在插入之前或之后在存储过程中执行额外的检查和处理。
Use a constraint (UNIQUE or PRIMARY KEY). That way the key is enforced for every application. You could perform additional checks and handling in a store procedure if you need to - either before or after the insert.