Creating a Stored Procedure with Dynamic SQL
Create a Stored Procedure with Dynamic SQL
Write a SQL query to create a stored procedure that uses dynamic SQL to execute a query based on user input.
Solution:
-- Create a stored procedure with dynamic SQL.
CREATE PROCEDURE ExecuteDynamicQuery
@TableName NVARCHAR(128), -- Input parameter for the table name.
@FilterColumn NVARCHAR(128), -- Input parameter for the filter column.
@FilterValue NVARCHAR(128) -- Input parameter for the filter value.
AS
BEGIN
DECLARE @SQL NVARCHAR(MAX);
-- Construct the dynamic SQL query.
SET @SQL = 'SELECT * FROM ' + QUOTENAME(@TableName) +
' WHERE ' + QUOTENAME(@FilterColumn) + ' = @FilterValue';
-- Execute the dynamic SQL query.
EXEC sp_executesql @SQL, N'@FilterValue NVARCHAR(128)', @FilterValue;
END;
Explanation:
- The goal is to create a stored procedure that dynamically constructs and executes a SQL query based on user-provided parameters.
- QUOTENAME : Ensures safe handling of table and column names to prevent SQL injection.
- sp_executesql : Executes the dynamic SQL query with parameterized inputs.
- Dynamic SQL allows you to build flexible queries that adapt to varying user inputs or conditions.
- For example, in reporting systems, you might use this procedure to generate custom reports based on user-selected filters.
1. Purpose of the Query :
2. Key Components :
3. Why Use Dynamic SQL? :
4. Real-World Application :
Additional Notes:
- Always sanitize inputs and use parameterized queries to prevent SQL injection attacks.
- Use this exercise to teach the risks and benefits of dynamic SQL in database programming.
For more Practice: Solve these Related Problems:
- Write a SQL query to create a stored procedure that dynamically constructs and executes a SELECT query based on a list of column names provided by the user.
- Write a SQL query to create a stored procedure that builds and runs an INSERT statement dynamically based on user-supplied values.
- Write a SQL query to create a stored procedure that generates a DELETE statement dynamically to remove records matching specific criteria.
- Write a SQL query to create a stored procedure that dynamically alters a table schema based on user-defined parameters.
Go to:
PREV : Create a Trigger for Cascading Updates.
NEXT : Create a Stored Procedure with Pagination.
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.