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
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.
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.
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')