Safe Dynamic SQL in SQL Server: Using sp_executesql, Parameters and QUOTENAME

Dynamic SQL is useful for flexible search screens and run-time sorting, but concatenating user input into query text opens the door to SQL injection. The article recommends passing values as parameters through sp_executesql, which keeps input out of the SQL text and allows query plan reuse. Because table and column names cannot be parameterized, they should be checked against an approved list and wrapped with QUOTENAME. It also notes that dynamic SQL runs under the caller's permissions, so access must be granted explicitly, and advises printing and testing the generated SQL with hostile input.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in