Stored procedure EXEC vs sp_executesql difference?

后端 未结 4 1803
逝去的感伤
逝去的感伤 2020-12-03 06:58

I\'ve written two stored procedure one with sp_executesql and other doesn\'t have sp_executesql both are executing properly same results, I didn\'t get what is

相关标签:
4条回答
  • 2020-12-03 07:03

    With sp_executesql, you don't have to build your query like that. You could declare it like this:

    DECLARE @SQL as nvarchar(128) = 'select ' + @Columns + ' from ' + 
    @TableName + ' where Status=@eStatus'
    

    This way if your @Status value came from a user you can use @eStatus and not have to worry about escaping '. sp_executesql gives you the ability to put variables in your query in string form, instead of using concatenation. So you have less to worry about.

    The column and table variables are still the same, but that's less likely to be directly from a user.

    0 讨论(0)
  • 2020-12-03 07:08

    Besides the usage, there are some important differences:

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

    2. sp_executesql can leverage cached query plans. The TSQL string is built only one time, after that every time same query is called with sp_executesql, SQL Server retrieves the query plan from cache and reuses it

    3. Temp tables created in EXEC can not use temp table caching mechanism

    0 讨论(0)
  • 2020-12-03 07:10

    Your sp_executesql SQL should probably be;

    DECLARE @SQL as nvarchar(128) = 'select ' + @Columns + ' from ' + 
                @TableName + ' where Status=@eStatus'
    

    This will allow you to call sp_executesql with @eStatus as a parameter instead of embedding it into the SQL. That will give the advantage that @eStatus can contain any characters and it will be properly escaped automatically by the database if required to be secure.

    Contrast that to the SQL required for EXEC;

    DECLARE @SQL as nvarchar(128) = 'select ' + @Columns + ' from ' + 
                @TableName + ' where Status=' + char(39) + @Status + char(39)
    

    ...where a char(39) embedded in @Status will make your SQL invalid and possibly create an SQL injection possibility. For example, if @Status is set to O'Reilly, your resulting SQL would be;

    select acol,bcol,ccol FROM myTable WHERE Status='O'Reilly'
    
    0 讨论(0)
  • 2020-12-03 07:23

    With Exec You can't have a place holder in your T-Sql statement string.

    sp_executesql gives you the advantage of having a place holder and pass the actual value at runtime

    0 讨论(0)
提交回复
热议问题