Hi, It is a SQL 2008 R2 server. I have a very large table with more than 2 million rows. I have a procedure: BEGIN TRAN CREATE PROCEDURE Test @StartDay DATE , @EndDay DATE , @xCreateDate DATETIME , @xUpdateDate DATETIME AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON ; -- Insert statements for procedure here --declare @s smalldatetime;set @s = cast('2011-03-01' as smalldatetime); --declare @f smalldatetime;set @f = cast('2011-03-31' as smalldatetime); SELECT * FROM Testtable WHERE ( InvoiceDate >= @StartDay AND InvoiceDate < @EndDay AND ( ( @xCreateDate = '' ) OR ( xCreateDate > @xCreateDate ) ) AND ( ( @xUpdateDate = '' ) OR ( xUpdateDate > @xUpdateDate ) ) ) END --**SQL statement:** SELECT * FROM Testtable WHERE ( InvoiceDate >= '7/1/2008' AND InvoiceDate < '8/1/2008' AND ( ( '' = '' ) OR ( xCreateDate > '' ) ) AND ( ( '' = '' ) OR ( xUpdateDate > '' ) ) ) ROLLBACK Below are the execution details when the SP is run as opposed to the select query being run: **When it is run for July data,** sql statement - 2273991 rows - 9 min 18 secs - Execution plan:table scan stored proc - 2273991 rows - 2 min 35 sec - Execution plan:RID lookup, index seek (invoice date) **When it is run for Aug data,** sql statement - 1920308 - 2.26 - RID lookup, index seek (invoice date) stored proc - 1920308 - 2.23 - RID lookup, index seek (invoice date) Questions Why is there such differences in the execution times and execution plans? There is an non-clustered index of invoicedate which is used when running the statements for Aug data. Can someone help me on this?? Thank you in advance..
It can be cause as follow: When the procedure was executed for the first time, it created a execution plan, which was cached. For the first time parameters which produced an index seek were passed. Then when you subsequently uses the procedure it is reusing existing plan and doing always an index seek and not table scan. In case of SQL statement, when the query is not parametric but you simply write the values, then the statements differ and for each query a new execution plan is being created. Therefore some values are causing the table scan and some index seek. The execution time difference is only a consequence of the plan. As the seeks takes less time that full table scan. You can have not up to date statistics. Try to update statistics and then try the select statements again. Also if you really want to compare the behavior of stored proc and the query, you need to clear the plan cache prior executing each of the commands using `DBCC FREEPROCCACHE` so you start the comparison from the same point.