我有以下SQL语句:
FUNCTION F1
INNER JOIN TABLE T1
INNER JOIN FUNCTION F2
INNER JOIN FUNCTION F3
INNER JOIN FUNCTION F4
...
INNER JOIN TABLE T2
在FUNCTION F1
未返回任何记录的情况下,wholes语句将在12
秒内执行。
FUNCTION F1
执行时间(单独)为4
秒。
如果我只离开加入FUNCTION F1
,则表格的exectuin时间再次为4
秒。
因此,SQL Server正在执行其余的函数,这会增加语句的执行时间。
为什么SQL Server没有跳过执行,因为有INNER JOIN
子句而第一个函数什么也没有返回?有没有办法解决这个问题?
答案 0 :(得分:0)
SQL引擎显然需要评估函数才能开始执行查询。如果有办法延迟这一点,我会感到惊讶。
一种选择是在运行查询之前进行检查:
select *
into #f1
from function f1;
if not exists (select 1 from #f1)
begin
-- stop processing here
end;
select *
into #f2
from function f2;
if not exists (select 1 from #f2)
begin
-- stop processing here
end;
select *
into #f3
from function f3;
if not exists (select 1 from #f3)
begin
-- stop processing here
end;
. . .
FUNCTION #F1
INNER JOIN TABLE T1
INNER JOIN #F2
INNER JOIN #F3
INNER JOIN #F4
...
INNER JOIN TABLE T2
这需要多个语句,但如果查询已经存储在存储过程中,则可能非常适合。