简体   繁体   中英

Best way to fix “maximum key length…” warning on multiple column unique constraint, E

I have to implement a Unique Combination of 4 different Columns in a table but I got this error :

Warning! The maximum key length is 900 bytes. The index 'a1_un' has maximum length of 1544 bytes. For some combination of large values, the insert/update operation will fail.

I understood the error and have an idea how to fix it (By changing the size of the columns). But which is the best way to eliminate this error and it works good. I've also read that it still works as its only a warning.

ADD CONSTRAINT a1_un UNIQUE([col1],[col2],[col3],[col4]);

col1, col2, col3, col4 are all NVARCHAR(256)

The 900 byte limit sure looks like SQL Server. The answer is you cannot do this directly. You can add a new column that reduces the size of the keys and implement a unique constraint on that.

alter table t
    add combined as (left(col1, 200) + '|' + left(col2, 200) + '|' + left(col3, 200) + '|' + left(col4, 200));

alter table t
    add constraint unq_t_combined unique(combined);

This is not exactly the same as your logic, but it might meet your needs.

Another alternative is to build the unique index on the hashes of the column values.

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