Skip to main content

sp_executesql( ) vs Execute() -- Dynamic Queries

There were few questions regarding "Passing table names as parameters to stored procedures" in Dotnetspider forums. I don't feel this to be a write way of coding. Still many persons are asking similar questions in the forums thought would write a post on "SP_EXECUTESQL()" Vs "EXECUTE()".

Sample SP to pass table name as parameter:

Create proc SampleSp_UsingDynamicQueries
@table sysname
As

Declare @strQuery nvarchar(4000)
Select @strQuery = 'select * from dbo.' + quotename(@table)

exec sp_executesql @strQuery -------- (A)
--exec (@strQuery) ---------------------- (B)
go

Test: Execute dbo.samplesp_usingdynamicqueries 'EmpDetails'

In the above stored procedure irrespective of whether we use the line which is marked as (A) or (B) it would give us the same result. So what's the difference between them?

One basic difference is while using (A) we need to declare the @strQuery as nvarchar or nchar.

(i) It would throw the below error if we declare @query as varchar data type.
Msg 214, Level 16, State 2, Procedure sp_executesql, Line 1
Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'.

(ii) It would throw the below error if we declare @query nvarchar(5000).
Msg 2717, Level 16, State 2, Procedure SampleSp_UsingDynamicQueries, Line 1
The size (5000) given to the parameter '@query' exceeds the maximum allowed (4000).


Hope the first point is well made!

Lets move to the next point, Exec statement is Unparameterised whereas sp_executeSql is Parameterised. What does it mean?

1. EXECUTE() :: If we write a query which takes a parameter lets say "EmpID". When we run the query with "EmpID" as 1 and 2 it would be creating two different cache entry (one each for value 1 and 2 respectively).

It means for Unparameterised queries the cached plan is reused only if we ask for the same id again. So the cached plan is not of any major use.

2. SP_EXECUTESQL() :: In the similar situation for "Parameterised" queries the cached plan would be created only once and would be reused 'n' number of times. Similar to that of a stored procedure. So this would have better performance.

Let me create a sample to illustrate this:

Create table dbo.EmpDetails
(
EmpID int,
EmpName varchar(30)
)
Go

Insert into dbo.EmpDetails values (1, 'Vadivel')
Insert into dbo.EmpDetails values (2, 'Sailakshmi')
Insert into dbo.EmpDetails values (3, 'Velias')
Go

Create table dbo.EmpTimeSheet
(
EmpID int,
Day varchar(10),
HrsPut float
)
Go

Insert into dbo.EmpTimeSheet values (1, 'Mon',7.5)
Insert into dbo.EmpTimeSheet values (1, 'Tue',2)
Insert into dbo.EmpTimeSheet values (1, 'Wed',8)
Insert into dbo.EmpTimeSheet values (2, 'Mon',9)
Insert into dbo.EmpTimeSheet values (2, 'Tue',8.3)
Insert into dbo.EmpTimeSheet values (2, 'Wed',11)
Go

Time to test it out:

DBCC Freeproccache
Go

Declare @strQuery nvarchar(1000)

Select @strQuery = 'Select E.EmpName, TS.Day, TS.HrsPut
from dbo.empdetails E, dbo.EmpTimeSheet TS
where E.EmpID = TS.EmpID and TS.EmpID = N''1'''
Exec (@strQuery)

Select @strQuery = 'Select E.EmpName, TS.Day, TS.HrsPut
from dbo.empdetails E, dbo.EmpTimeSheet TS
where E.EmpID = TS.EmpID and TS.EmpID = N''2'''
Exec (@strQuery)

Select @strQuery = 'Select E.EmpName, TS.Day, TS.HrsPut
from dbo.empdetails E, dbo.EmpTimeSheet TS
where E.EmpID = TS.EmpID and TS.EmpID = @EmpID'
Exec sp_executesql @strQuery, N'@EmpID int', 1
Exec sp_executesql @strQuery, N'@EmpID int', 2

After this lets have a look at the cached plan by executing the below query. The first two (Unparameterised) has a execution_count of 1, the last one (Parameterised) would have an execution_count of 2.

Select sqlTxt.text, qStats.execution_count from sys.dm_exec_query_stats qStats
Cross Apply (Select [text] from sys.dm_exec_sql_text(qStats.sql_handle)) as sqlTxt option (Recompile)

DBCC Freeproccache has been used to just flush out all already cached plan and make our life easier to see our queries plan alone :)

Extract from MSDN: Use DBCC FREEPROCCACHE to clear the procedure cache. Freeing the procedure cache causes, for example, an ad hoc SQL statement to be recompiled instead of reused from the cache.

Please note: Run this statement only in Development Server and not in Production box :)

If you want to test it in SQL Server 2000 box, then query the system table "syscacheobjects".

Select cacheobjtype, usecounts, sql from syscacheobjects

Hope this helps!

Related Article: The curse and blessings of Dynamic SQL

Technorati tags: ,

Comments

Anonymous said…
You are asking to be shot in the head if you write SPs that take user input and execute them.

First target of hackers wanting to rip through using SQL injection.
Vadivel said…
Very true Pandu. Thats the reason I have mentioned its not the write way to code :) Also i have provided a link "Curse and Blessing of Dynamic SQL" .. there is a topic on sql injection there too.
Anonymous said…
I have 4 variables that are OUTPUT variables (to be used subsequently in my sp) in my sp_executesql call. But I get an error:

Server: Msg 8144, Level 16, State 2, Line 0
Procedure or function has too many arguments specified.

So how do I retrieve the OUTPUT variables data?

Appreciate your help.

Thanks.
Anonymous said…
I am working on a similar SP that has a tablename input but also has a date input paramter and here it is

USE sample
GO
CRETAE PROCEDURE select_tab @tblname sysname, @date date
AS
Declare @sdate date
set @sdate = @date
DECLARE @sql varchar(max)
SET @sql = 'SELECT *
FROM dbo.' + quotename(@tblname)
select @sdate = (cast(@date as varchar(10)))

EXEC sp_executesql @sql
--------------------------- UNTIL HERE IT WORKS FINE BUT BELOW EXEC IS NOT WORKING

exec select_tab @tblname = Teacher2, N'@date = 2010-03-15'

I get an error message

Msg 119, Level 15, State 1, Line 1
Must pass parameter number 2 and subsequent parameters as '@name = value'. After the form '@name = value' has been used, all subsequent parameters must be passed in the form '@name = value'.


Could you please let me know where I am going wrong? I would really appreciate your help!

Popular posts from this blog

Script table as - ALTER TO is greyed out - SQL SERVER

One of my office colleague recently asked me why we are not able to generate ALTER Table script from SSMS. If we right click on the table and choose "Script Table As"  ALTER To option would be disabled or Greyed out. Is it a bug? No it isn't a bug. ALTER To is there to be used for generating modified script of Stored Procedure, Functions, Views, Triggers etc., and NOT for Tables. For generating ALTER Table script there is an work around. Right click on the table, choose "Modify" and enter into the design mode. Make what ever changes you want to make and WITHOUT saving it right click anywhere on the top half of the window (above Column properties) and choose "Generate Change Script". Please be advised that SQL Server would drop actually create a new table with modifications, move the data from the old table into it and then drop the old table. Sounds simple but assume you have a very large table for which you want to do this! Then it woul

AWS fatal error: An error occurred (400) when calling the HeadObject operation: Bad Request

While using AWS and trying to copy a file from a S3 bucket to my EC2 instance ended up with this error message. Command Used: aws s3 cp s3://mybucketname/myfilename.html /var/www/html/ Error: fatal error: An error occurred (400) when calling the HeadObject operation: Bad Request The error goes off if we add the region information to the command statement. I am using Asia Pacific (Mumbai) so used ap-south-1 as the region name. Modified Command: aws s3 cp s3://mybucketname/myfilename.html /var/www/html/ --region ap-south-1

[Non Tech] Want to know the recipe for Omelette :)

Fed up with Bread - Jam and Curd Rice, today i wanted to eat Omelette. Interesting part is I wanted to cook it myself :) So in the first picture you see all the items which are needed for preparing an Omelette. When I had a closer look at the eggs I see that almost all the eggs are broken. But believe me when I bought it couple of days back it was in perfect condition! I was wondering whether the eggs have become rotten or pretty old to consume! I tried taking an egg and break it but couldn't break it at all :) Since I have kept in the freezer all the eggs have frozen and looked like a iron ball :) After trying for few minutes of trying i removed the shell of the egg and then kept that iron ball :) into a bowl and placed it within Oven. I heated it for 1 minute and checked. It melted only to a limit. So i just set it for another 2 minutes and checked it later. It has melted but the part of the egg white has become a Omelette :( I didn't leave it there. I took the bowl out of