使 varchar(500) 数据列唯一
我需要使 varchar(500) 列唯一。
放置唯一约束将不起作用,因为它超出了唯一的大小限制。
那么,让专栏独一无二的最佳策略是什么?
I have a requirement to make a column of varchar(500) unique.
Putting unique constraint would not work as it crosses the size limit of unique.
Then, what would be the best strategy to make column unique?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用该
varchar(500)
的 HASH 创建另一个字段,并在该哈希字段上添加UNIQUE CONSTRAINT
:HASHBYTES('md5', MyLongVarcharField)
这会导致性能不佳,但如果您有一个
varchar(500)
,您需要强制唯一性,我假设性能不是您考虑的首要因素无论如何。编辑:
澄清一下,两个字符串输出相同 128 位哈希值的几率是
340,282,366,920,938,000,000,000,000,000,000,000,000 中的 1
。发生碰撞的可能性不大,但也不是绝对不可能。如果您仍然担心,可以使用 160 位的
SHA
或SHA1
算法。Create another field with the HASH of that
varchar(500)
, and put aUNIQUE CONSTRAINT
on the hash field:HASHBYTES('md5', MyLongVarcharField)
This will cause poor performance but if you have a
varchar(500)
where you need to enforce uniqueness I'm assuming performance isn't on the forefront of your considerations anyways.EDIT:
To clarify, the chance of having two strings output the same 128 bit hash value is
1 in 340,282,366,920,938,000,000,000,000,000,000,000,000
. It's unlikely but not categorically impossible that you could have a collision.If you are still concerned you can use
SHA
orSHA1
algorithms which are 160 bits.您可以在 INSERT 和 UPDATE 上使用 DML 触发器。这可以避免必须使用哈希。为简单起见,我选择了 AFTER 触发器,但这也可以使用 INSTEAD OF 触发器轻松完成。
You can use a DML trigger on INSERT and UPDATE. This gets around having to use a hash. I chose an AFTER trigger for simplicity, but this can be easily done with an INSTEAD OF trigger as well.