SQL Server - 与 NULL 相比非常慢

标签 sql asp.net sql-server performance

我想加快下面的查询

WHERE子句中有两个条件(引用下面的查询)

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

关于如何加快速度的任何想法?表中大约有 70 万行,而且只会增长。

(注意:下面显示的查询被剥离到它的本质,我严格使用硬编码值来简化查询,以便将焦点吸引到上面概述的部分)

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

最佳答案

你能把它分成两个查询吗? or 通常会给优化器带来问题:

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 相比非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27194253/

相关文章:

java - SQL服务器异常: when using jdbc connection to retrieve data

java - 使用来自两个不同数据库的两个表通过 JOOQ 构建左连接查询

javascript - 用于从二进制流(字节数组)播放的视频播放器

sql - 将 SQL 结果分组/聚合到 1 小时的桶中

c# - 如何在 C# 中从另一个表达式创建一个表达式?

sql - 将字母转换为数字

sql - 主键 (a,b) 与主键 (b,a) 不同吗?

javascript - 使用javascript下载文件弹出框

asp.net - 客户端回调和 Ajax 页面方法之间的区别 - ASP.NET

sql - sql server中两个连续日期之间的差异(以天为单位)