![]() |
In SQL Server, at times the SQL Queries need to be dynamic and not static, meaning the complete SQL query may be built dynamically at run time as a string using the user inputs and any specific application logic. This can be done in queries run from back-end applications or inside stored procedures. In this article let us look into the details about how to create a dynamic SQL and its uses and also what are the security issues that may arise and how to handle those security issues. What is a Dynamic SQL?Generally, when we write a SQL Query, the SQL Statement or the Stored procedure SQL Statements are fully written as static statements which do not change at run time or once it is compiled initially. But there could be scenarios where the Table Name, Column Name list, the ‘WHERE‘ clause values, or any part of the query may be generated at run time from user inputs. So, this technique of dynamically constructing and executing SQL statements at run time based on user inputs which helps to create flexible and adoptable queries is referred to as Dynamic SQL in SQL Server. Building a dynamic SQL string can be determined by factors like string concatenation, parameter values, user input values, Stored procedure parameters, values received from calling a function or result from another subquery or any application logic. Syntax: Variable Name = SQL String Explanation:
Example of Dynamic SQLDeclare @sqlString nvarchar(2000),@strStudentGrade varchar(10) Output: ![]() Dynamic Query Explanation The variable ‘@sqlString‘ holds the dynamic SQL created using the string concatenation and variables. Here the variable ‘@strStudentGrade‘ has the value for the Student Grade. Once the dynamic SQL is built it can be run using the EXEC or sp_executesql commands. Above bexample uses the EXEC command. The same can be run using sp_executesql command like below: EXEC sp_executesql @sqlString But the sp_executesql, a built-in system stored procedure is used mainly for parameterized queries. Dynamic SQL for Dynamic FilteringDynamic Filtering is a method in SQL Server dynamic query to filter data for different filter conditions dynamically for the same SQL query. The Filter condition could be an user input received from the front-end and passed to a dynamic query. Example of Dynamic FilteringCreate Procedure spFilterStudentData This stored procedure can be run using the below execution command: EXEC spFilterStudentData 'Ramesh' Output: ![]() Dynamic Filtering Explanation: In the above example, the Student Name is filtered dynamically using a stored procedure with dynamic SQL to create the filter dynamically. When the stored procedure is executed with ‘Ramesh‘ as filter data, the above result is displayed from the ‘Students‘ table. Dynamic SQL for Dynamic SortingDynamic sorting using dynamic SQL in SQL Server is a method to sort one or more columns of a dynamic query result set dynamically and flexibly. By this method, the user can determine the sorting order of the result set at runtime instead of being hardcoded in the query. Example of Dynamic SortingCreate Procedure spSortStudentData This stored procedure can be run using the below execution command: Exec spSortStudentData 'Student_Name' Output: ![]() Dynamic Sorting Explanation: In the above example the Student table data can be displayed by passing the column name by which the user wants to ‘Sort‘ the data, and as an example the table data is sort by ‘Student_Name‘ by sending this column name value when the stored procedure ‘spSortStudentData‘ is executed. Dynamic SQL for Schema ModificationsDuring run time Table Schema changes can be done using dynamic SQL based on user inputs or application logic. A typical Schema modification includes adding a new table or adding a new column to an existing table using dynamic SQL. Create Procedure AddNewTableDynamicSQL User can execute the stored procedure as below to create a new table: EXEC AddNewTableDynamicSQL 'Customers', 'CustID', 'CustomerName', 'CustomerLocation' Another example of Adding the column to an existing table: CREATE Procedure AddNewColumnDynamicSQL User can execute the stored procedure as below to create a add a new column to existing table: EXEC AddNewColumnDynamicSQL 'Customers','CustomerPhone','varchar(50)' Dynamic SQL for Parameterized QueriesParameterized queries in Dynamic SQL is a method of building a SQL Query with parameters and this helps avoid security issues. Declare @sqlquery nvarchar(1000),@sqlGrade char(1) Ouput: ![]() Dynamic SQL for Parameterized Queries Uses of Dynamic SQLDynamic SQL helps to create flexible, adaptable, and reusable SQL queries that can be applied to different scenarios and situations in fetching data from SQL Server. Some of the general uses of Dynamic SQL are given below:
Dynamic SQL and Security RisksWhen a SQL query is constructed using user input, this can lead to SQL injection attacks. So it is advised to use dynamic SQL with caution and check all data input by users to avoid any security risks. It is always advisable to use parameterized queries to prevent SQL injection attacks. ConclusionDynamic SQL queries in SQL Server are a great option to generate dynamic and re-usable code which offers a lot of flexibility and avoid code repetition. But utmost care should be taken to avoids security issues since dynamic SQL generated using user input can lead to SQL injection attacks. |
Reffered: https://www.geeksforgeeks.org
Databases |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |