sql query takes more time when run in a view

后端 未结 3 1302
悲哀的现实
悲哀的现实 2021-01-25 06:23

HI all,

I have a huge sql query. When i put that query in a stored Proc it takes 5 seconds to execute which i run it just as a query it takes 4-5 seconds but when i run

相关标签:
3条回答
  • 2021-01-25 06:41

    I agree with Vash in that the additional time when run as a vaiew may be due to the extra time to compile an execution plan.

    Try running this

    Set Statistics Time On
    Select * from view
    
    and then Set Statistics On
    Exec yourSPHere
    

    You'll get something like this

    SQL Server parse and compile time:
    CPU time = 0 ms, elapsed time = 1 ms.

    SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms.

    (5475 row(s) affected) Table 'ContactBase'. Scan count 1, logical reads 428, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

    SQL Server Execution Times: CPU time = 47 ms, elapsed time = 470 ms.

    If the "SQL Server parse and compile time:" accounts for the difference between the two times that your answer is that the View is having to Create a execution plan each time while the Sproc is using a cached execution plan.

    0 讨论(0)
  • 2021-01-25 06:48

    Tip: replace

    CASE WHEN freight IS NULL THEN 0 ELSE freight END AS FREIGHT, 
    

    with

    ISNULL(freight, 0);
    

    When You use the stored procedure the execution plan is compiled and stored so SQL Engine do not have to create it.

    When You run this as query You probably have this plan already in cache, that why there is no diff in execution.

    Probably when you are using the view the execution plan has to created from scratch.

    0 讨论(0)
  • 2021-01-25 06:55

    Based on your comment, I suspect you hitting the "predicate pushing" issue (search for this phrase)

    Observation... the WHERE on the LEFT JOIN changes this to a JOIN

    LEFT JOIN RefCountry As DestRefCountry...
    ....
    where (DestRefCountry.RN_Desc = 'United States')
    
    0 讨论(0)
提交回复
热议问题