![]() |
VOOZH | about |
Dynamic SQL is a technique where SQL statements are built and executed at runtime instead of being fixed. It allows queries to change based on user input, conditions, or program logic, making applications more flexible and powerful when working with databases.
It is useful when:
The basic syntax for Dynamic SQL involves creating a query string and executing it using tools like sp_executesql in SQL Server:
Syntax:
EXEC sp_executesql N'SELECT statement';The N prefix indicates that the SQL statement is treated as a Unicode string.
The table below highlights the key distinctions between Static SQL and Dynamic SQL for better understanding.
| Static SQL | Dynamic SQL |
|---|---|
| SQL statements are predefined in the code. | SQL statements generated at runtime. |
| Limited to predefined queries. | Highly flexible for dynamic scenarios. |
| Faster, as it is precompiled. | Slower, as it requires runtime parsing. |
| Fixed queries and repetitive tasks. | Dynamic conditions and user-defined inputs. |
Follow these steps to create and execute Dynamic SQL in SQL Server:
1. Declare Variables: Declare two variables, @var1 for holding the name of the table and @var 2 for holding the dynamic SQL :
DECLARE
@var1 NVARCHAR(MAX),
@var2 NVARCHAR(MAX);2. Assign Values to Variables: Set the value of the @var1 variable to table_name :
SET @var1 = N'table_name';3. Construct the SQL Statement: Create the dynamic SQL by adding the SELECT statement to the table name parameter :
SET @var2= N'SELECT *
FROM ' + @var1;4. Execute the SQL Statement: Run the sp_executesql stored procedure by using the @var2 parameter :
EXEC sp_executesql @var2;Dynamic SQL is a technique where SQL statements are built and executed at runtime instead of being fixed. It allows queries to change based on user input, conditions, or program logic, making applications more flexible and powerful when working with databases.
👁 Screenshot-2026-01-30-175826The following script dynamically retrieves data from the geek table:
Query:
DECLARE @tab NVARCHAR(128);
DECLARE @st NVARCHAR(MAX);
SET @tab = N'geektable';
SET @st = N'SELECT * FROM ' + QUOTENAME(@tab);
EXEC sp_executesql @st;Output:
👁 Screenshot-2026-01-30-175826Here are some key advantages of dynamic SQL:
Here are some disadvantages of dynamic SQL:
These tips help make Dynamic SQL safe and efficient: