SQL Server 2016:WHERE语句评估

时间:2016-09-07 13:38:59

标签: sql-server

我有类似的东西

declare @par int = null

select 
    count(distinct(t1.id))
from 
    my_table t1
left outer join 
    some_other t2 on t1.a = t2.b
where 
    @par is null or t2.c = @par

@par为空。注释掉这个where子句后,查询很快,当取消注释时 - 慢。结果是一样的。

为什么呢?难道不能发现第一部分或陈述是真的而不评估第二部分吗?如何最好地解决这个问题(当@par为空时快速解决)。

SQL Server 2016

2 个答案:

答案 0 :(得分:3)

WHERE替换为AND ()

select count(distinct(t1.id))
from my_table t1
left outer join some_other t2 on t1.a = t2.b
AND ( @par is null or t2.c = @par )

答案 1 :(得分:2)

试试这个,

declare @par int = null

IF @par is null
BEGIN
    select count(distinct(t1.id))
    from my_table t1
END
ELSE BEGIN
    select count(distinct(t1.id))
    from my_table t1
         inner join some_other t2 on t1.a=t2.b
    where t2.c = @par
END

如果您希望使用左连接方法,请尝试下面,它将阻止在参数具有NULL值时加载连接表。

select count(distinct(t1.id))
from my_table t1
    left outer join some_other t2 on t1.a=t2.b
        and @par is not null    -- it will prevent loading the table when @par is null
where 
    @par is null or t2.c = @par