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: SQL Server, SQL Server 2005
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: SQL Server, SQL Server 2005
Comments
First target of hackers wanting to rip through using SQL injection.
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.
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!