Stored procedure EXEC vs sp_executesql difference?

后端 未结 4 1811
逝去的感伤
逝去的感伤 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: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'
    

提交回复
热议问题