SQL Server 2008 - HashBytes计算列

时间:2010-09-12 20:34:02

标签: .net sql sql-server sql-server-2008

我正在使用SQL Server 2008。

我有一个名为Title 的 NVARCHAR(MAX)列,我想为它添加一个唯一索引。 因为列大于900字节,我决定创建一个HashBytes计算列(基于对StackOverflow的建议)。

如何创建HashBytes列?

alter table Softs add TitleHash AS (hashbytes('SHA1',[Title])) PERSISTED;

这很有效,并且已经创建了计算列。

但是在尝试添加索引时出现以下错误

Adding the selected columns will result in an index key with a maximum length of 8000 bytes.  
The maximum permissible index length is 900 bytes. 
INSERT and UPDATE operations fail if the combined value of the key columns exceeds 900 bytes.  
Do you want to continue?

这是用于创建索引的查询:

CREATE NONCLUSTERED INDEX [UIX_TitleHash] ON [dbo].[Softs] 
(
    [TitleHash] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

1 个答案:

答案 0 :(得分:33)

hashbytes列被创建为VARBINARY(MAX),除非你明确告诉它20个字节是充足的:

alter table dbo.Softs 
  add TitleHash AS CAST(hashbytes('SHA1', [Title]) AS VARBINARY(20)) PERSISTED

完成后,您可以在该列上创建索引(唯一或不唯一):

CREATE UNIQUE NONCLUSTERED INDEX [UIX_TitleHash] 
  ON [dbo].[Softs]([TitleHash] ASC)

现在这应该可以正常工作。