简体   繁体   English

SQL Server唯一约束问题

[英]SQL Server unique constraint problem

How to create a unique constraint on a varchar(max) field in visual studio, visually. 如何在visual studio中的varchar(max)字段上创建唯一约束。

the problem is when i try it: 问题是我试试的时候:

manage indexes and keys > add > columns 管理索引和键>添加>列

I can only chose the bigint columns, but not any of the varchar(max) ones. 我只能选择bigint列,但不能选择任何varchar(max)列。

Do I maybe have to use check constraints ? 我是否可能必须使用检查约束

If yes, what to put in the expression? 如果是的话,在表达中放什么?

Thnx for the info Thnx的信息

You cannot put a unique constraint on a VARCHAR(MAX) column (which could be up to 2 GB of text!!). 您不能在VARCHAR(MAX)列上放置唯一约束(可能最多2 GB的文本!!)。 You just simply cannot. 你根本就不能。

The unique constraint is enforced by a unique index in the background, and SQL Server has a 900 byte limit on index entries. 唯一约束由后台中的唯一索引强制执行,SQL Server对索引条目具有900字节的限制。 You also cannot put a unique constraint on a VARCHAR(2000) field for that reason. 由于这个原因,您也无法在VARCHAR(2000)字段上放置唯一约束。

You'll need to find another way to achieve what you're trying to do. 你需要找到另一种方法来实现你想要做的事情。 You could eg calculate the length and something like a checksum over your text and put a unique constraint on those length and checksum columns. 您可以例如计算长度以及类似于文本的校验和,并对这些长度和校验和列设置唯一约束。

Even if this were possible, it would be a bad idea. 即使这是可能的,这也是一个坏主意。

1) There is another way. 1)还有另一种方式。 Find some other data to use as your unique column 查找其他一些数据以用作您的唯一列

2) If you ABSOLUTELY HAVE TO use the varchar(Max). 2)如果你绝对必须使用varchar(Max)。 Maybe hash it on insert/update and add a hash column? 也许在插入/更新时散列并添加哈希列?

One way to do this would be to add a column for a hash that is calculated whenever you insert or update the column and put a unique index on that. 执行此操作的一种方法是为每次插入或更新列时计算的哈希添加列,并在其上添加唯一索引。 While hash collisions do happen, it is extremely unlikely. 虽然哈希冲突确实发生,但不可能。

You could use this T-SQL keyword: 您可以使用此T-SQL关键字:

http://msdn.microsoft.com/en-us/library/ms174415.aspx http://msdn.microsoft.com/en-us/library/ms174415.aspx

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

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