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

Registry manipulation from SQL

Registry Manupulation from SQL Server is pretty easy. There are 4 extended stored procedure in SQL Server 2000 for the purpose of manupulating the server registry. They are: 1) xp_regwrite 2) xp_regread 3) xp_regdeletekey 4) xp_regdeletevalue Let us see each one of them in detail! About xp_regwrite This extended stored procedure helps us to create data item in the (server’s) registry and we could also create a new key. Usage: We must specify the root key with the @rootkey parameter and an individual key with the @key parameter. Please note that if the key doesn’t exist (without any warnnig) it would be created in the registry. The @value_name parameter designates the data item and the @type the type of the data item. Valid data item types include REG_SZ and REG_DWORD . The last parameter is the @value parameter, which assigns a value to the data item. Let us now see an example which would add a new key called " TestKey ", and a new data item under it called TestKeyValue :

Screen scraping using XmlHttp and Vbscript ...

I wrote a small program for screen scraping any sites using XmlHttp object and VBScript. I know I haven't done any rocket science :) still I thought of sharing the code with you all. XmlHttp -- E x tensible M arkup L anguage H ypertext T ransfer P rotocol An advantage is that - the XmlHttp object queries the server and retrieve the latest information without reloading the page. Source code: < html > < head > < script language ="vbscript"> Dim objXmlHttp Set objXmlHttp = CreateObject("Msxml2.XMLHttp") Function ScreenScrapping() URL == "UR site URL comes here" objXmlHttp.Open "POST", url, False objXmlHttp.onreadystatechange = getref("HandleStateChange") objXmlHttp.Send End Function Function HandleStateChange() If (ObjXmlHttp.readyState = 4) Then msgbox "Screenscrapping completed .." divShowContent.innerHtml = objXmlHttp.responseText End If End Function </ script > < head > < body > &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