Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a sp which has no input parameters .I also have dynamic sql statemtns build and executed usign sp_executesql.My question is when we execute the sp more than once ..will the execution plan that is generated for the first time is reused or not?
Here is the code block:
SQL
CREATE proc uspcachehitchk
as
begin
DECLARE @sal bigint;
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
declare @dbsortorder varchar(100)
set @dbsortorder='desc'
declare @cols nvarchar(1000)
set @cols=N'empno,ename,job,mgr,SAL'
declare @size int
set @size=4
SET @SQLString =
   N'select top(@size) '+ @cols + ' from emp where sal>Convert(varchar(100),@sal) order by ename '+ @dbsortorder;
SET @ParmDefinition = N'@sal bigint,@cols nvarchar(100),@size int';
SET @sal= 2000;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
           @sal= @sal,@cols=@cols,@size=@size;
           end


I have used SP:cachehit and SP:cachemiss events in the profiler to trace ..but i could only see the select statement is firing sP:cachehit..but not the sp.IS this the correct way to check for execution plan reuse..or if there exists any other please help me .

Regards
Chaithanya M
Posted
Updated 28-Jul-11 19:05pm
v2

According to MSDN: 'The Transact-SQL statement or batch in the sp_executesql stmt parameter is not compiled until the sp_executesql statement is executed. The contents of stmt are then compiled and executed as an execution plan separate from the execution plan of the batch that called sp_executesql'

http://msdn.microsoft.com/en-us/library/ms188001.aspx[^]
 
Share this answer
 
To expand on Manas' answer... please see snippet from the link he provided:

sp_executesql can be used instead of stored procedures to execute a Transact-SQL statement many times when the change in parameter values to the statement is the only variation. Because the Transact-SQL statement itself remains constant and only the parameter values change, the SQL Server query optimizer is likely to reuse the execution plan it generates for the first execution.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900