SQL Server › Stored Procedures & Functions

What is the difference between using EXEC and calling a stored procedure through parameterized application code, and why does this distinction matter for security?

Intermediate

Answer

Calling a stored procedure properly through parameterized application code passes user input as distinct parameters that SQL Server treats strictly as data, while carelessly using EXEC to build and run a dynamic string that includes concatenated user input can expose your application to SQL injection if that input is not properly validated and escaped first.
-- Safe: proper parameterized call
EXEC GetCustomerOrders @CustomerId = 123;

-- Risky if built from unsanitized user input
EXEC ('SELECT * FROM Orders WHERE CustomerId = ' + @UserInput);
Real-world example A development team reviews their codebase and finds a legacy piece of code building a dynamic EXEC statement directly from user input, refactoring it to use a proper parameterized stored procedure call instead to eliminate the SQL injection risk.

Common follow-ups: How do you audit an existing codebase for unsafe dynamic SQL patterns like this?;What tools can help automatically detect potential SQL injection vulnerabilities?