When I generate sql schema creation scripts manually I usually just call 'Create Procedure...', however I notice that when you generate the script using the Tasks/Generate Scripts option it uses 'spexecutesql @statement = ..' e.g.
EXEC dbo.sp_executesql @statement = N'-- =============================================
-- Author: Me
-- Create date: 20/03/2009
-- Description: Does stuff
-- =============================================
CREATE PROCEDURE [dbo].[MyProc]
-- Add the parameters for the stored procedure here
@StartDate datetime
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
...
END
'
Why is this? Is it something about retaining comments? Thanks
The primary purpose of using the sp_executesql stored procedure is to run dynamic SQL queries. Dynamic SQL queries are those built at runtime based on one or more variable values.
The sp_executesql stored procedure is used to execute dynamic SQL queries in SQL Server. A dynamic SQL query is a query in string format. There are several scenarios where you have an SQL query in the form of a string.
Return values are generally not used to "return" a result but to return success (0) or an error number (1-65K). The above all seem to indicate that sp_executesql does not return a value, which is not correct. sp_executesql will return 0 for success and any other number for failure.
sp_executesql allows for statements to be parameterized, Therefore It's more secure than EXEC in terms of SQL injection.
It has nothing to do with comments. It does it that way only when you tell it to "include IF NOT EXISTS". The reason is that it can only programmatically include or exclude objects if they are executed dynamically.
You can disable this is stored procedures by selecting "False" in Options\SQL Server Object Explorer\Scripting - Check for object existence.
I realize this is old, but the fix is buried pretty deep in Sql 2012. Michael Haren is right, the method of rendering sprocs changes when Object Existence Checks are required in Options. To change this, go to Options, Sql Server Object Explorer, Scripting, Object Scripting Options, and set 'Check for object existence' to false. Sprocs now render 'normally', without using sp_executesql.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With