字符长度的900字节索引大小限制

ief*_*fpw 38 sql-server indexing sql-server-2012

SQL Server 2012具有900字节索引限制的字符总限制是多少.我创建了一个列varchar(2000),但我认为它超过了SQL Server限制的900字节?什么是最大值varchar(?)以适应900字节索引列?

Tim*_*ner 49

varchar的存储大小是输入数据的实际长度+ 2个字节.即使列本身具有2字节开销,您也可以将最多900字节的 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.
Run Code Online (Sandbox Code Playgroud)

请注意,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
Run Code Online (Sandbox Code Playgroud)

对于通常对于索引键来说太大的这些列,您可以通过它们包含在索引中来获得索引的一些好处.


lmi*_*gle 9

在相关的说明中,您可以尝试使用另一个选项来获取宽列的索引,请参阅http://www.brentozar.com/archive/2013/05/indexing-wide-keys-in-sql-server /其中哈希列添加到表中,然后在查询中编制索引并使用.

  • 我使用`HASHBYTE`功能效果很好,谢谢!OP正在讨论SQLServer2012,但请注意`SHA2_512`算法仅在SQLServer2012中引入,因此如果您使用的是早期版本,则必须使用不同的算法,因为为早期版本指定`SHA2_512`只返回`null`!这是[2008年的文档](http://technet.microsoft.com/en-us/library/ms174415%28v=sql.100%29.aspx).例如:`选择HASHBYTES('SHA2_512','快速棕狐')为sha2_512,HASHBYTES('MD5','快速棕狐')为md5,HASHBYTES('SHA1','快速棕狐')作为sha1`. (2认同)

The*_*war 6

对于使用SQLServer 2016的服务器,索引键大小已增加到1700字节。. 数据库引擎-SQL Server 2016中的新增功能

NONCLUSTERED索引的最大索引键大小已增加到1700字节。

演示:

create table test
(
id varchar(800),
id1 varchar(900)
)

insert into test
select replicate('a',800),replicate('b',900)

create index nci on test(id,id1)
Run Code Online (Sandbox Code Playgroud)