Problem Statement
You must build dynamic SQL for a flexible report. How do you keep it safe and fast?
Explanation
Allow only whitelisted identifiers (columns, sort keys). Bind user values as parameters so the engine can reuse plans and injection is blocked. Expose a wrapper stored procedure with EXECUTE permissions, not direct table access.
Log the final statement and role for audit. Add resource guards such as row limits and timeouts, and index the columns your dynamic filters hit most.
Code Solution
SolutionRead Only
-- SQL Server sample DECLARE @sql nvarchar(max)=N'SELECT col_list FROM t WHERE status=@s'; EXEC sp_executesql @sql, N'@s nvarchar(10)', @s=@in_status;
Practice Sets
This question appears in the following practice sets: