gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:37:10 25 4
gpt4 key购买 nike

我有一个包含两列的表格。当我尝试为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com