Wednesday, June 4, 2008

When and where do we use hash index in sql server

参考http://www.fotia.co.uk/fotia/Blog/2006/01/hash-indexes.html
当我设计一个Product表的时候, 对于ProductName这个字段的数据类型, 我一直拿捏不定, 最后为了不至于ProductName被截断, 我选用了NVarchar(4000), 我没有选择Text(NText)类型, 因为在SQL Server 2005中,它们被标记为Deprecated.
幸运的是,我选取了NVarchar(4000), 在实际情况下, 有个名称也确实够长, 足足1000个byte.
同时我又需要在ProductName上创建Index, 对于length>=900byte的字段, 将SQL Server拒绝为你创建普通的index.
怎么办呢? 我们可以为ProductName这样的长字段, 创建Hash Index, 方法是:
第一步, 为Product表创建一个计算列, 比如ProductNameHashField, 让它的值为CheckSum(ProductName), 这个字段的值将是Integer类型.
第二步, 创建一个ProductNameHashField字段的Index, 名为IX_Product_NameHash


-- Index it. Note that this is a non-unqiue index for collisions.
create index IX_Product_NameHash
on Product(ProductNameHashField);
go

怎么利用这个Hash Index, 来加速我们的query呢?


-- Look for the hash of the DName.
-- Always, always include the original data in case of collisions.
select customerId
from Product
where ProductNameHashField= checksum(@ProductName)-- this is the key to speed up query
and ProductName= @ProductName
go

通过观察执行计划, 发现查询速度确实有了很大的提高.

No comments: