Stored Procedures - Executing & Dynamic SQL
From SQLServerPedia
|
See Also: Main_Page - Transact SQL Coding Techniques - Reusable Coding Techniques - Stored Procedures The permission to execute a stored procedure defaults to its owner. However you can use the GRANT statement to grant the permission to a procedure to other users, as follows: GRANT EXECUTE ON byroyalty TO PUBLIC
Sp_executesql can be used to call any statement or batch, not just a stored procedure. Executing SQL statements that are built "on the fly" is referred to as dynamic SQL. You can use either sp_executesql or the EXECUTE command to execute your dynamic SQL statements. The following paragraphs summarize the usage of each alternative. The system stored procedure sp_executesql behaves very similar to the EXECUTE command, however, it offers two advantages:
The following query shows how to build a query string dynamically with sp_executesql and EXECUTE: DECLARE @string NVARCHAR(100) SELECT @string = 'select * from authors' EXEC sp_executesql @string
DECLARE @string VARCHAR(100) SELECT @string = 'select * from authors' EXEC (@string)
DECLARE @string VARCHAR(100), @qty INT SELECT @qty = 20 SET @string = 'select * from sales where qty > ' + CONVERT(VARCHAR(2), @qty) EXEC (@string)
DECLARE @string NVARCHAR(100), @qty INT SET @qty = 20 SET @string = 'select * from sales where qty > @qty' EXEC sp_executesql @string, N'@qty int', @qty
You can pass system or user-defined functions to the EXEC or sp_executesql. For instance the following statements behave identically: Functions with sp_executesql: DECLARE @string NVARCHAR(100), @qty INT SET @qty = 20 SET @string = 'select stor_id, sum(qty) from sales group by stor_id having sum(qty) > @qty' EXEC sp_executesql @string, N'@qty int', @qty
DECLARE @string VARCHAR(100), @qty INT SELECT @qty = 20 SET @string = 'select stor_id, sum(qty) from sales group by stor_id having sum(qty) > ' + CONVERT(VARCHAR(2), @qty) EXEC (@string)
DECLARE @string NVARCHAR(100) SET @string = 'declare @qty int '+ char(10) SET @string = @string + 'SET @qty = 20 ' + char(10) SET @string = 'select stor_id, sum(qty) from sales group by stor_id having sum(qty) > @qty' EXEC sp_executesql @string, N'@qty int', @qty
Sp_executesql behaves identically to EXEC when it comes to changing the database context. If you change the database context within the stored procedure or batch and execute that module with sp_executesql or EXEC, you'll be back to the database where you started as soon as the module is done executing. Similarly, the SET commands issued within the context of EXEC or sp_executesql do not affect the main block of code and are effective only while the dynamic SQL is executing. On the other hand, the SET commands used in a batch prior to calling the dynamic SQL will have effect on how dynamic SQL executes. Related ReadingHere's some more blog posts and wiki articles about dynamic T-SQL:
|