varchar 的存储大小是输入数据的实际长度 + 2 个字节。即使列本身有 2 个字节的开销,您最多可以将 900 byte varchar 值放入索引的列中。
实际上,您可以在大于 900 字节的列上创建索引,但如果您实际尝试插入大于900 字节:
create table test (
col varchar(1000)
);
create index test_index on test (col);
-- Warning! The maximum key length is 900 bytes. The index 'test_index' has maximum length of 1000 bytes. For some combination of large values, the insert/update operation will fail.
insert into test select cast(replicate('x', 899) as varchar(1000)); -- Success
insert into test select cast(replicate('y', 900) as varchar(1000)); -- Success
insert into test select cast(replicate('z', 901) as varchar(1000)); -- Fail
-- Msg 1946, Level 16, State 3, Line 8
-- Operation failed. The index entry of length 901 bytes for the index 'test_index' exceeds the maximum length of 900 bytes.
请注意,900 字节的限制包括给定索引键的所有列,如下例所示:
create table test (
col varchar(1000)
, otherCol bit -- This column will take a byte out of the index below, pun intended
);
create index test_index on test (col, otherCol);
insert into test select cast(replicate('x', 899) as varchar(1000)), 0; -- Success
insert into test select cast(replicate('y', 900) as varchar(1000)), 0; -- Fail
insert into test select cast(replicate('z', 901) as varchar(1000)), 0; -- Fail
对于这些通常对于索引键来说太大的列,您可以通过在索引中通过including 对它们进行索引来获得一些好处。