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

My Wedding Anniversary :)

Six years back on the same day I married Sai Lakshmi (12-July-2000). I know Sai for almost 13 years now :) I fell in love with her during my 12th standard. I know @ 17 yrs any person wouldn't be matured enough to make a big decision like this. But thank God my choice was perfect :) Even now, very often we used to think about the past and laugh at our behaviors/actions then. My love story would be really interesting (at least for me and Sai :)) and I am sure none of you guys would be interested in reading about it so lemme not get into it in-depth. But one thing which I want to share is "Without Sai, I wouldn't have entered into the IT field at all". She was instrumental in convincing me to study my Master's degree in Computer Application. That's the move that changed my career. Till my schooling, my dream was to either become a "big" sportsman (Cricket and Badminton were my favorites at that time.) or an Aeronautics engineer. Unfortunately, my l...

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

What should one look @ while buying a land in chennai?

Offlate people have started thinking about investing their money in lands. I too think that to be a wise decision only! As most of us know buying a land in chennai (for that matter any where in the world) isn't an easy affair. I was just wondering what all one needs to look at before deciding to purchase a land. I thought I would put down what ever I know about this subject here. [Guys pls free to correct me if I my understanding is wrong somewhere. That way, it would help me understand as well as others who might read this in future]. Here we go ... 1. One should not buy farm lands if they want to build a residential house sometime later there. Because to my knowledge its illegal to build residential houses on lands meant for irrigation. 2. Encumberance Certificate -- This is what is shortly refered as "EC". One needs to get an EC from local sub registrar office (i guess we need pay a small amount for this). From this we / our lawyers :) can find out whether the guy who ...