Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does sql server generate stored procedures using sp_executesql statement with string?

Tags:

sql-server

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

like image 572
Mark Avatar asked May 07 '09 23:05

Mark


People also ask

Why we use sp_executesql in SQL Server?

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.

What is sp_executesql stored procedure?

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.

What does sp_executesql return?

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.

What are the benefits of using sp_executesql over EXEC?

sp_executesql allows for statements to be parameterized, Therefore It's more secure than EXEC in terms of SQL injection.


2 Answers

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.

like image 171
Michael Haren Avatar answered Sep 27 '22 19:09

Michael Haren


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.

like image 36
Thomas McNamee Avatar answered Sep 27 '22 21:09

Thomas McNamee