我正在使用sql Server 2008.
我有一个名为Title的NVARCHAR(MAX)列,我想添加一个唯一的索引.
因为列大于900bytes,我决定创建一个HashBytes计算列(基于StackOverflow上的推荐).
如何创建HashBytes列?
alter table Softs添加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
解决方法
哈希字节列被创建为一个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)
现在这应该是正常的.