Originally published at SQL & Cloud Lab .
This post was drafted with AI assistance.
Dynamic SQL, building a query as a string and executing it, is sometimes the right tool: flexible search screens, choosing a sort column at run time, or maintenance scripts that loop over tables. It is also the classic route to SQL injection. The rules for doing it safely are short and strict.
The dangerous way
-- DO NOT DO THIS DECLARE @ sql NVARCHAR ( MAX ) = N 'SELECT * FROM dbo.Employee WHERE FullName = '' ' + @ Name + N ' '' ' ; EXEC ( @ sql );
Enter fullscreen mode
Exit fullscreen mode
If @Name contains x'; DROP TABLE dbo.Employee; -- , it becomes part of the SQL and runs.…