Back to results for “Error Handling with TRY CATCH”
SQL Server › Dynamic SQL

What is dynamic SQL, and why would you need to build and execute a SQL statement as a string rather than writing it directly?

Beginner

Answer

Dynamic SQL means building a SQL statement as a text string at runtime and then executing it, which is useful when parts of your query, such as the table name or the columns being sorted by, are not known ahead of time and depend on some condition or user input determined while the program is running.
DECLARE @TableName NVARCHAR(100) = 'Orders';
DECLARE @SQL NVARCHAR(MAX) = 'SELECT * FROM ' + @TableName;
EXEC (@SQL);
Real-world example A reporting tool lets users choose which table to generate a report from through a dropdown menu, using dynamic SQL to build the correct query based on whichever table the user actually selected.

Common follow-ups: What are the security risks associated with building dynamic SQL from user input?;What is the difference between using EXEC and sp_executesql to run dynamic SQL?