SQL Server的 - 相比为NULL很慢 [英] SQL Server - Comparing to NULL very slow

查看:454
本文介绍了SQL Server的 - 相比为NULL很慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想加快下面的查询

有WHERE子句中的两个条件(见下面的查询,以供参考)

目前,大约需要60秒。但是,如果我删除where子句中的第一个条件(@Query为NULL),那么它几乎立即返回。

我如何能加快有什么想法?在表中关于700K行,这样只会增加。

(注:下面显示的查询被剥​​离下来到它的本质裸露,我使用硬codeD值严格简化查询,以便焦点向上述的画出的部分)

 声明@Query为nvarchar(255)
选择@Query ='海洋'选择
    *
从(选择
  ROW_NUMBER()OVER(ORDER BY b.BookTitle)为ROWNUMBER,
  湾*

  图书B(NOLOCK)
哪里
  - 如果我删除这个首要条件@Query是NULL,那么它​​几乎立即返回
  - 否则,如果我保持这个位置,它需要大约1分钟
  - 是的,我有BOOKTITLE全文索引,以及普通索引。
  (@Query为NULL)或(包括(b.BookTitle,@Query))
)为T1其中,40至60岁t1.RowNumber


解决方案

可以拆分成两个查询呢? 往往会造成一个问题,优化:

 如果@Query为null
开始
    选择 *
    从(选择ROW_NUMBER()OVER(ORDER BY b.BookTitle)为ROWNUMBER,B *。
          从书本B(NOLOCK)
          其中,@Query为NULL
         )为T1
    其中,40至60岁t1.RowNumber;
结束
其他
开始
    选择 *
    从(选择ROW_NUMBER()OVER(ORDER BY b.BookTitle)为ROWNUMBER,B *。
          从书本B(NOLOCK)
          其中,包含(b.BookTitle,@Query)
         )为T1
    其中,40至60岁t1.RowNumber;
结束

I want to speed up the following query

There are two conditions in the WHERE clause (see below query for reference)

Currently, it takes about 60 seconds. However, if I remove the first condition in the where clause (@Query is NULL) then it returns almost immediately.

Any thoughts on how I can speed up? About 700k rows in the table and this will only grow.

(Note: The query shown below is stripped down to it's bare essence and I'm using hardcoded values strictly to simplify the query so that the focus is drawn toward the portion outlined above)

declare @Query nvarchar(255)
select @Query = 'oceans'

select
    * 
from

(select 
  row_number() over( order by b.BookTitle) as RowNumber, 
  b.*
from
  Books b (nolock)
where
 -- If I remove this first condition "@Query is NULL", then it returns almost immediately
 -- Otherwise if I keep this here, it takes around 1 minute
 -- Yes, I have full-text index on BookTitle, as well as a regular index.
  (@Query is NULL) or (contains(b.BookTitle, @Query))
) as t1

where t1.RowNumber between 40 and 60

解决方案

Can you split this into two queries? or often causes a problem for optimizers:

if @Query is null
begin
    select * 
    from (select row_number() over( order by b.BookTitle) as RowNumber, b.*
          from Books b (nolock)
          where @Query is NULL
         ) as t1
    where t1.RowNumber between 40 and 60;
end
else
begin
    select * 
    from (select row_number() over( order by b.BookTitle) as RowNumber, b.*
          from Books b (nolock)
          where contains(b.BookTitle, @Query)
         ) as t1
    where t1.RowNumber between 40 and 60;
end

这篇关于SQL Server的 - 相比为NULL很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆