标量函数和子查询之间的区别

时间:2013-07-25 06:18:16

标签: sql sql-server-2008 function view subquery

我在View中遇到问题。我不能在这里向你展示确切的View因为它违反了发展政策小组的政策
以下是视图的格式:

Create View View_Name as
Select A,B,C,D,E,F
  from  (
    Select  T.A,T.B,T.C,T.D,
        dbo.Function_1(T1.A,T2.B) E,
        dbo.Function_2(T1.A,T2.B) F,
        dbo.Function_3(T1.A,T2.B) G,
      from  (
        Select  T1.A,T1.B,T2.C,T2.D
          from  Table1 T1 
          join  Table2 T2
            on  Some_Condition_1
             .
             .
             .
         where  Some_Where_Clause
         group  by T1.A,T1.B,T2.C,T2.D
        ) T
     where  Some_Where_Condition_ForThis_InnerQuery
    ) T_Out
 where Some_Where_Conditions_For_OuterQuery

此视图需要5分钟才能执行。 每个表中有40,000条记录。

但是,当我用functions替换Queries时,执行速度非常快。执行只需要2秒钟。


I don't want to re-format my View, but I wanted to know why the execution time is 
different in both cases?

1 个答案:

答案 0 :(得分:0)

我认为问题是SQL服务器无法优化它必须为每一行调用它的函数调用。对于子查询,优化器可以完成其工作。

有很多讨论:

Why is a UDF so much slower than a subquery?

Performance, User Defined Function or Sub Query