How to use sp_executesql to avoid SQL Injection

前端 未结 2 1351
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 03:17

In the below sample code, Table Name is an input parameter. In this case, how can I avoid SQL injection using sp_executesql. Below is the sample code, I am trying t

2条回答
  •  情话喂你
    2021-01-22 04:15

    You can enclose the table name in []

    SET @sql= N'  select * from [' + @tblname + '] where name= @param1 and id= @param2'; 
    

    However, if you use a two-part naming convention e.g dbo.tablename, you have to add additional parsing, since [dbo.tablename] will result to:

    Invalid object name [dbo.tablename].

    You should parse it so that it'll be equal to dbo.[tablename].

提交回复
热议问题