title: How to use sp_executesql to avoid SQL Injection
body: <p>In the below sample code, Table Name is an input parameter. In this case, how can I avoid SQL injection using <code>sp_executesql</code>. Below is the sample code, I am trying to use <code>sp_executesql</code>to avoid it but it doesn't work. Can anyone tell me how to correct it?</p>
  
  <pre><code>ALTER PROC Test @param1  NVARCHAR(50), 
                   @param2  INT, 
                   @tblname NVARCHAR(100) 
  AS 
    BEGIN 
        DECLARE @sql NVARCHAR(1000) 
  
        SET @sql= N'  select * from ' + @tblname 
                  + ' where name= @param1 and id= @param2'; 
  
        PRINT @sql 
  
        EXEC Sp_executesql 
          @sql, 
          N'@param1 nvarchar(50), @param2 int', 
          @param1, 
          @param2; 
    END 
  
  EXEC Test 
    'John', 
    2, 
    ' emp; delete from emp where id = 567; select * from emp ' 
  </code></pre>
  
  <p>Output: 
  Print message:</p>
  
  <pre><code>select * from  emp; delete from emp where id = 567; select * from emp  where name= @param1 and id= @param2;
  </code></pre>
  
  <p>All the input parameters are exactly substituted and one row is deleted.
  Please let me know how to handle this scenario.</p>