SQL Server › Dynamic SQL
What is SQL injection, and how does it relate to writing dynamic SQL unsafely?
BeginnerAnswer
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 onesReal-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.