简体   繁体   English

在 SQL Server 中索引 NVARCHAR(MAX) 列

[英]Indexing an NVARCHAR(MAX) column in SQL Server

When I define a column as NVARCHAR(MAX) , I can't index that column.当我将一列定义为NVARCHAR(MAX) ,我无法索引该列。 But I certainly can't define the column as NVARCHAR(4000) since I assume the data string will be longer sometimes.但我当然不能将列定义为NVARCHAR(4000)因为我认为数据字符串有时会更长。

Can anyone suggest how to index the column with NVARCHAR(MAX) data definition or is it possible to increase the length from 4000 to more?任何人都可以建议如何使用NVARCHAR(MAX)数据定义对列进行索引,或者是否可以将长度从 4000 增加到更多?

  1. You have either nvarchar(4000) or nvarchar(max).您有 nvarchar(4000) 或 nvarchar(max)。 Nothing in between中间什么都没有
  2. Maximum length of the index key column(s) together is 900 bytes, so you can't index nvarchar(4000) either (which is 8000 bytes)索引键列的最大长度加在一起是 900 字节,因此您也不能索引 nvarchar(4000)(即 8000 字节)

Personally, I can't see why you need to index nvarchar(max).就个人而言,我不明白为什么需要索引 nvarchar(max)。
Are you seriously going to search for strings up to 1GB long?您真的要搜索长达 1GB 的字符串吗?

Anyway, your only option is to use HASHBYTES in a persisted computed column.无论如何,您唯一的选择是在持久计算列中使用HASHBYTES
You create a hash of the column, and index the HASH.您创建列的散列,并索引散列。

Note, depending on what version you may not be able to hash nvarchar(max)请注意,根据您可能无法对 nvarchar(max) 进行哈希处理的版本

For SQL Server 2014 and earlier, allowed input values are limited to 8000 bytes.对于 SQL Server 2014 及更早版本,允许的输入值限制为 8000 字节。

SQL Server 2016 code example that also enforces uniqueness也强制执行唯一性的 SQL Server 2016 代码示例
The SHA2_512 hash gives the least chance of collision. SHA2_512 散列给出的碰撞机会最小。 For a sufficiently large table a weaker hash like MD4 will hit the birthday problem对于足够大的表,像 MD4 这样较弱的散列会遇到生日问题

CREATE TABLE dbo.HashExample (
    SomeID int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
    SomeLongText nvarchar(MAX) NULL,
    SomeHash AS HASHBYTES('SHA2_512', SomeLongText) PERSISTED
)
GO
CREATE UNIQUE INDEX UX_SomeHash ON dbo.HashExample(SomeHash) WHERE SomeLongText IS NULL
GO

INSERT dbo.HashExample (SomeLongText) VALUES ('Row 1'), ('Row 2')
GO
SELECT * FROM dbo.HashExample
GO

DECLARE @LookFor nvarchar(MAX) = 'Row 3'
SELECT * FROM dbo.HashExample WHERE SomeHash = HASHBYTES('SHA2_512', @LookFor)
SET @LookFor = 'Row 2'
SELECT * FROM dbo.HashExample WHERE SomeHash = HASHBYTES('SHA2_512', @LookFor)
GO

Note, you can't have LIKE searches.请注意,您不能进行 LIKE 搜索。 Only = or <>只有=<>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM