SQL Server › Dynamic SQL

What is SQL injection, and how does it relate to writing dynamic SQL unsafely?

Beginner

Answer

SQL injection is a security vulnerability where an attacker inserts malicious SQL code into an input field, which then gets concatenated directly into a dynamic SQL string and executed as part of your query, potentially letting them view, modify, or delete data they should never have access to.
-- Vulnerable: directly concatenating user input
DECLARE @UserInput NVARCHAR(100) = 'Test'' OR ''1''=''1';
DECLARE @SQL NVARCHAR(MAX) = 'SELECT * FROM Users WHERE Name = ''' + @UserInput + '''';
-- This could return all rows instead of just matching ones
Real-world example A poorly built login form that concatenates a username directly into a dynamic SQL query is exploited by an attacker who enters a specially crafted value, bypassing authentication entirely due to SQL injection.

Common follow-ups: How does using parameterized queries prevent SQL injection?;What other precautions help protect against SQL injection beyond avoiding string concatenation?