2012-10-03 177 views
32

SQL Server 2012具有的900字節索引限制的總字符限制是多少?我創建了一個有varchar(2000)的列,但我認爲它超過了SQL Server限制的900字節?在900字節的索引列中放入什麼是最大的varchar(?)字符長度中的900字節索引大小限制

+0

可能取決於該字符集的表使用 –

+0

我所使用的最小字符集有每字符1個字節。猜測你的至少是那麼大。 – keyser

+0

這是一個SQL Server 2012 64位軟件。沒有什麼特別的字符集。只需Windows 8 64位即可運行SQL Server 2012 64位開箱即用。美國英語的Windows。 – iefpw

回答

47

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索引獲得一些好處。

8

在一個相關的說明,您可以嘗試,對一個寬列得到一個指數的另一種選擇,在那裏http://www.brentozar.com/archive/2013/05/indexing-wide-keys-in-sql-server/哈希列添加到表中,然後編入索引,在查詢中使用的概述。

+2

我使用了'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'。 – DarthPablo

1

對於那些在SQLServer的2016年,索引鍵的大小增加到1700個字節.. What's new in Database Engine - SQL Server 2016

最大索引鍵的大小非聚簇索引已經增加到1700個字節。

演示:(?拉丁語-8859)

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)