SQL Topics
Dynamic SQL
title: Dynamic SQL
In the previous lesson, you learned about:
MERGE Statement
UPSERT Operations
Data SynchronizationNow we move to the final topic of the:
Advanced SQLmodule.
The topic is:
Dynamic SQLDynamic SQL is one of the most powerful and advanced SQL concepts used in enterprise applications.
Unlike normal SQL queries:
Static SQLwhich are written before execution,
Dynamic SQL allows SQL statements to be:
Generated
Modified
Executedat runtime.
This provides enormous flexibility for applications, reporting systems, and administration tools.
What is Dynamic SQL?
Dynamic SQL is SQL code that is generated and executed during runtime rather than being written completely beforehand.
Example:
Static SQL:
SELECT *
FROM Employees;Query is fixed.
Dynamic SQL:
SELECT *
FROM + TableName;Table name can change during execution.
Simple Definition
Dynamic SQL is SQL code that is constructed as a string and executed at runtime.
Why is Dynamic SQL Needed?
Suppose a reporting system allows users to choose:
Table
Columns
Filters
Sortingbefore generating reports.
A fixed query cannot handle every possibility.
Dynamic SQL solves this problem.
Static SQL vs Dynamic SQL
Static SQL
Written before execution.
Example:
SELECT *
FROM Employees;Always executes the same query.
Dynamic SQL
Built during execution.
Example:
DECLARE @SQL VARCHAR(500);
SET @SQL =
'SELECT * FROM Employees';
EXEC(@SQL);Comparison Table
| Feature | Static SQL | Dynamic SQL |
|---|---|---|
| Query Fixed | Yes | No |
| Runtime Changes | No | Yes |
| Performance | Better | Slightly Lower |
| Flexibility | Limited | High |
| Complexity | Low | Higher |
How Dynamic SQL Works
Process:
Build Query String
↓
Store In Variable
↓
Execute QueryBasic Dynamic SQL Syntax
SQL Server:
DECLARE @SQL VARCHAR(500);
SET @SQL =
'SELECT * FROM Employees';
EXEC(@SQL);Understanding the Syntax
DECLARE
Creates SQL string variable.
SET
Stores query text.
EXEC()
Executes query string.
First Example
DECLARE @SQL VARCHAR(500);
SET @SQL =
'SELECT * FROM Employees';
EXEC(@SQL);Result:
Employee Records ReturnedDynamic WHERE Clause
Requirement:
Filter By DepartmentExample:
DECLARE @Department VARCHAR(50);
SET @Department = 'HR';
DECLARE @SQL VARCHAR(500);
SET @SQL =
'SELECT *
FROM Employees
WHERE Department = '''
+ @Department +
'''';
EXEC(@SQL);Generated Query
SELECT *
FROM Employees
WHERE Department = 'HR';Dynamic Table Name
Requirement:
User Selects TableExample:
DECLARE @TableName VARCHAR(100);
SET @TableName =
'Employees';
DECLARE @SQL VARCHAR(500);
SET @SQL =
'SELECT *
FROM '
+ @TableName;
EXEC(@SQL);Generated Query
SELECT *
FROM Employees;Dynamic Column Selection
Example:
DECLARE @ColumnName VARCHAR(100);
SET @ColumnName =
'EmployeeName';
DECLARE @SQL VARCHAR(500);
SET @SQL =
'SELECT '
+ @ColumnName +
' FROM Employees';
EXEC(@SQL);Generated Query
SELECT EmployeeName
FROM Employees;Dynamic ORDER BY
Example:
DECLARE @SortColumn VARCHAR(100);
SET @SortColumn =
'Salary';
DECLARE @SQL VARCHAR(500);
SET @SQL =
'SELECT *
FROM Employees
ORDER BY '
+ @SortColumn;
EXEC(@SQL);Generated Query
SELECT *
FROM Employees
ORDER BY Salary;Dynamic INSERT
Example:
DECLARE @SQL VARCHAR(500);
SET @SQL =
'INSERT INTO Employees
VALUES
(
1,
''Rahul'',
50000
)';
EXEC(@SQL);Dynamic UPDATE
Example:
DECLARE @SQL VARCHAR(500);
SET @SQL =
'UPDATE Employees
SET Salary = 60000
WHERE EmployeeID = 1';
EXEC(@SQL);Dynamic DELETE
Example:
DECLARE @SQL VARCHAR(500);
SET @SQL =
'DELETE FROM Employees
WHERE EmployeeID = 1';
EXEC(@SQL);EXEC vs sp_executesql
SQL Server provides:
EXEC()
sp_executesqlEXEC()
Basic execution.
Example:
EXEC(@SQL);sp_executesql
Advanced execution.
Supports:
Parameters
Caching
Security
PerformanceExample
DECLARE @SQL NVARCHAR(500);
SET @SQL =
N'SELECT *
FROM Employees
WHERE Salary > @MinSalary';Execution:
EXEC sp_executesql
@SQL,
N'@MinSalary INT',
@MinSalary = 50000;Why sp_executesql is Better
Benefits:
Safer
Faster
Reusable
ParameterizedSQL Injection Risk
Major concern with Dynamic SQL.
Dangerous Example
SET @UserInput =
''' OR 1=1 --';Generated query:
SELECT *
FROM Users
WHERE Username = ''
OR 1=1;Result:
Security BreachWhat is SQL Injection?
SQL Injection occurs when attackers insert malicious SQL code into application inputs.
It is one of the most common database security vulnerabilities.
Prevention Techniques
Use:
Safe Example
EXEC sp_executesql
@SQL,
N'@Username VARCHAR(50)',
@Username = @Input;Real-World Example: Reporting System
User chooses:
Department
Date Range
SortingDynamic SQL builds custom report queries.
Real-World Example: E-Commerce
User selects:
Category
Price Range
BrandDynamic filtering generated automatically.
Real-World Example: Banking
Requirement:
Custom Financial ReportsDynamic SQL generates reports based on user-selected criteria.
Real-World Example: University System
Requirement:
Dynamic Student ReportsBased on:
Department
Semester
CGPAReal-World Example: Payroll
Generate:
Monthly Payroll Reports
Department Reports
Tax Reportsusing Dynamic SQL.
Advantages of Dynamic SQL
High Flexibility
Query changes at runtime.
Supports Dynamic Reporting
Major use case.
Reduces Duplicate Code
Reusable query generation.
Supports Metadata-Driven Systems
Useful in enterprise applications.
Powerful Administration Tool
Used by DBAs.
Disadvantages of Dynamic SQL
SQL Injection Risk
Most serious concern.
Harder Debugging
Generated queries can be difficult to trace.
Performance Overhead
Parsing occurs at runtime.
Complex Maintenance
Large dynamic queries become difficult to manage.
Common Mistakes
Ignoring SQL Injection
Most dangerous mistake.
String Concatenation Errors
Missing quotes cause failures.
Using EXEC Everywhere
Prefer sp_executesql when possible.
Poor Input Validation
Security vulnerability.
Best Practices
Prefer sp_executesql
More secure and efficient.
Validate User Input
Always sanitize inputs.
Use Parameters
Avoid string concatenation.
Log Generated Queries
Helps debugging.
Limit Dynamic SQL Usage
Use only when necessary.
Dynamic SQL vs Stored Procedures
| Feature | Dynamic SQL | Stored Procedure |
|---|---|---|
| Runtime Changes | Yes | No |
| Security | Lower | Higher |
| Performance | Moderate | Better |
| Flexibility | High | Limited |
| Maintenance | Harder | Easier |
Common Interview Questions
What is Dynamic SQL?
SQL code generated and executed at runtime.
Why is Dynamic SQL used?
To create flexible queries based on runtime requirements.
What is SQL Injection?
A security attack that injects malicious SQL into queries.
Which is better: EXEC or sp_executesql?
sp_executesqlbecause it supports parameters and improves security.
What is the biggest risk of Dynamic SQL?
SQL InjectionSummary
Dynamic SQL allows SQL statements to be generated and executed at runtime, providing flexibility for reporting systems, enterprise applications, administration tools, and data-driven platforms. While powerful, it must be used carefully because improper implementation can lead to security vulnerabilities such as SQL Injection.
In this lesson, you learned:
- What Dynamic SQL is
- Static SQL vs Dynamic SQL
- EXEC()
- sp_executesql
- Dynamic Filtering
- Dynamic Tables
- SQL Injection
- Security Best Practices
- Real-world Examples
- Advantages and Disadvantages
Mastering Dynamic SQL is important because enterprise applications often require flexible query generation based on user input and business requirements.
Advanced SQL Module Completed ✅
Completed files:
Next Folder
Next Topic → Query Optimization
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Dynamic SQL.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this SQL topic.
Search Terms
sql, sql complete guide, sql tutorial, sql notes, complete, guide, advanced, dynamic
Related SQL Topics