Menu

Dynamic SQL Done Safely: sp_executesql, Parameters and QUOTENAME
📰

Dynamic SQL Done Safely: sp_executesql, Parameters and QUOTENAME

DEV Community: database·LingamSuyambu·13 days ago
#f3ga26vO
#devtodatabase#devto#dev#name#deptid
Long article (753 words) — no AI summary yet.
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.