sql - 在 SQL Server 中创建索引时收到警告消息

标签 sql sql-server t-sql indexing sql-server-2012

我有一个包含两列的表格。当我尝试为 NVARCHAR(2000) 列创建索引时,它显示警告消息,例如:

Warning! The maximum key length is 900 bytes

但是索引是在 SQL Server 中为此表创建的:

Create Table Test
(
     Id Int primary key,
     ProdName Nvarchar(2000)
)

插入了 100 万条记录。

Created index ix_Test on Test(ProdName)

SQL Server 是否会在 where 条件下的 ProdName 列上使用此索引?因为它创建时带有警告消息。

Like 运算符通常不使用索引吗?

最佳答案

创建索引时,SQL Server 正在检查列的元数据。 SQL Server 2012 的最大索引长度为 900 字节,SQL Server 2016 的最大索引长度为 1700 字节。

对于 NVARCHAR(2000) 最大大小(以字节为单位)为 4000,它超出了索引的最大限制。

Create Table Test(Id Int primary key,ProdName Nvarchar(2000));
INSERT INTO Test VALUES (1, REPLICATE('0123456789',45));
Create index ix_Test ON Test(ProdName);
INSERT INTO Test VALUES (2, REPLICATE('0123456789',46));
-- Operation failed. The index entry of length 920 bytes for the index    
--'ix_Test' exceeds the maximum length of 900 bytes.

db<>fiddle demo

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


这意味着您的列中的字符串值短于 450 个字符(900 字节)。

SELECT MAX(DATALENGTH(ProdName))
FROM Test;
-- should be lower than 900

至于第二个问题,只要条件是SARGable,就会使用索引:

SELECT *
FROM Test
WHERE ProductName = 'ABC' -- index usage;

SELECT *
FROM Test
WHERE ProductName = 'AB%'; -- index usage

SELECT *
FROM Test
WHERE ProductName LIKE '%B%'; -- no index seek, index/table scan instead

关于sql - 在 SQL Server 中创建索引时收到警告消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53801643/

相关文章:

SQL查询多个select语句

mysql - SQL语法=显示 "one table"内的关系+一张关系表

python - 将 XML 导入 SQL 数据库

sql-server - DB2 中的@@error 有什么相同之处?

sql - 复杂的 SQL 查询帮助。在 SQL 中形成查询

SQL Server 2014 - SQL 配置管理器中未安装任何服务

java - SQL BLOB 不以空值结尾。我该怎么做?

t-sql - 查询以查找提供所有服务的所有提供商

t-sql - 在 SQL 中使用 EXISTS 作为列

SQL Server - 从一个表中选择多行数据并使用第一个选定的数据更新另一个表上的多行数据