Dynamic SQL in stored procedures is a powerful feature that allows SQL queries to be constructed and executed at runtime. This chapter provides a comprehensive guide to understanding, implementing, and optimizing Dynamic SQL within stored procedures, covering everything from the basics to advanced techniques. Each section is designed to build your knowledge step-by-step with clear explanations and practical examples.
Dynamic SQL refers to SQL statements that are built and executed dynamically during the runtime of an application or stored procedure. Unlike static SQL, which is predefined and fixed, dynamic SQL is flexible and can adapt to varying requirements.
Dynamic SQL is typically constructed using string concatenation or interpolation to form complete SQL statements.
DECLARE @TableName NVARCHAR(50) = 'Employees';
DECLARE @DynamicSQL NVARCHAR(MAX);
SET @DynamicSQL = 'SELECT * FROM ' + @TableName;
PRINT @DynamicSQL;
SELECT * FROM Employees
The EXEC
statement can execute a dynamically constructed SQL string.
DECLARE @TableName NVARCHAR(50) = 'Employees';
DECLARE @DynamicSQL NVARCHAR(MAX);
SET @DynamicSQL = 'SELECT * FROM ' + @TableName;
EXEC(@DynamicSQL);
sp_executesql
is a safer and more efficient way to execute dynamic SQL. It supports parameterized queries, reducing the risk of SQL injection.
DECLARE @DynamicSQL NVARCHAR(MAX);
DECLARE @Department NVARCHAR(50) = 'HR';
SET @DynamicSQL = 'SELECT * FROM Employees WHERE Department = @Dept';
EXEC sp_executesql @DynamicSQL, N'@Dept NVARCHAR(50)', @Department;
@DynamicSQL
variable contains the query template.@Dept
is passed safely to the query.Dynamic SQL can be seamlessly integrated into stored procedures to handle scenarios requiring flexible logic.
CREATE PROCEDURE GetEmployeesByFilter
@ColumnName NVARCHAR(50),
@Value NVARCHAR(50)
AS
BEGIN
DECLARE @DynamicSQL NVARCHAR(MAX);
SET @DynamicSQL = 'SELECT * FROM Employees WHERE ' + @ColumnName + ' = @FilterValue';
EXEC sp_executesql @DynamicSQL, N'@FilterValue NVARCHAR(50)', @Value;
END;
GO
EXEC GetEmployeesByFilter 'Department', 'HR';
List of employees from the HR department.
Dynamic SQL is susceptible to SQL injection if user input is directly concatenated into the query. To prevent this:
sp_executesql
.
SET @DynamicSQL = 'SELECT * FROM Employees WHERE Name = ''' + @UserInput + '''';
EXEC(@DynamicSQL); -- Vulnerable to SQL Injection
SET @DynamicSQL = 'SELECT * FROM Employees WHERE Name = @Name';
EXEC sp_executesql @DynamicSQL, N'@Name NVARCHAR(50)', @UserInput;
sp_executesql
allows better reuse of execution plans compared to EXEC
.PRINT
to inspect the generated SQL.
BEGIN TRY
EXEC sp_executesql @DynamicSQL;
END TRY
BEGIN CATCH
PRINT 'Error: ' + ERROR_MESSAGE();
END CATCH;
Pivoting transforms rows into columns dynamically.
DECLARE @Columns NVARCHAR(MAX), @DynamicSQL NVARCHAR(MAX);
-- Generate column names
SELECT @Columns = STRING_AGG(QUOTENAME(Department), ',') FROM Employees;
-- Construct the dynamic PIVOT query
SET @DynamicSQL = '
SELECT *
FROM (SELECT Name, Department FROM Employees) AS SourceTable
PIVOT (COUNT(Name) FOR Department IN (' + @Columns + ')) AS PivotTable;
';
EXEC sp_executesql @DynamicSQL;
sp_executesql
: Always prefer parameterized execution.Dynamic SQL in stored procedures adds flexibility and power to database programming, enabling the handling of complex scenarios such as dynamic table names, flexible filtering, and advanced reporting. By adhering to best practices, using tools like sp_executesql, and focusing on security, developers can harness the full potential of dynamic SQL while maintaining performance and safety. This chapter provides a detailed roadmap to mastering dynamic SQL, ensuring you can apply it confidently in real-world applications. Happy coding !❤️