The Wayback Machine - https://web.archive.org/web/20240721202456/https://www.geeksforgeeks.org/dynamic-sql-in-sql-server/
Open In App

Dynamic SQL in SQL Server

Last Updated : 27 Dec, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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:

  • Variable Name is the name of the variable where the Dynamic SQL is stored as a String.
  • SQL String is the string that contains the SQL Statement using variables to represent dynamic elements like table names, column names, or conditions in the ‘WHERE‘ clause.

Example of Dynamic SQL

Declare @sqlString nvarchar(2000),@strStudentGrade varchar(10)
Set @strStudentGrade= 'A'
Set @sqlString='Select * from Students Where Grade=' + char(39) + @strStudentGrade + char(39)
EXEC(@sqlString)

Output:

DynamicQuery

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 Filtering

Dynamic 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 Filtering

Create Procedure spFilterStudentData
@strStudentName nvarchar(100)
As
Begin
Declare @SqlQuery nvarchar(1000)
Set @SqlQuery= 'Select * from Students where Student_Name =' + CHAR(39) + @strStudentName + CHAR(39)
Exec(@SqlQuery)
End

This stored procedure can be run using the below execution command:

EXEC spFilterStudentData 'Ramesh'

Output:

DynamicQueryFilter

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 Sorting

Dynamic 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 Sorting

Create Procedure spSortStudentData
@strOrderBy nvarchar(30)
As
Begin
Declare @SqlQuery nvarchar(1000)
Set @SqlQuery= 'Select * from Students Order By ' + @strOrderBy
Exec(@SqlQuery)
End

This stored procedure can be run using the below execution command:

Exec spSortStudentData 'Student_Name'

Output:

DynamicQuerySorting

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 Modifications

During 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
(
@TableName varchar(30),
@ColumnName1 varchar(30),
@ColumnName2 varchar(30),
@ColumnName3 varchar(30)
)
As
Begin
Declare @SQLString nvarchar(1000)
Set @SQLString='Create Table ' + QUOTENAME(@TableName) + '(' + QUOTENAME(@ColumnName1) +
'varchar(50),' + QUOTENAME(@ColumnName2) + 'varchar(50),' + QUOTENAME(@ColumnName3) + 'varchar(50))'
EXEC sp_executesql @SQLString
End

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
(
@TableName varchar(30),
@ColumnName1 varchar(30),
@DataType varchar(30)
)
As
Begin
Declare @SQLString nvarchar(1000)
Set @SQLString='ALTER TABLE ' + QUOTENAME(@TableName) + ' ADD ' + QUOTENAME(@ColumnName1) + ' ' + @DataType
EXEC sp_executesql @SQLString
End

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 Queries

Parameterized 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)
Set @sqlquery='Select * from Students where Grade=@eGrade'
Set @sqlGrade='B'
EXEC sp_executesql @sqlquery, N'@eGrade char(1)', @eGrade =@sqlGrade
Here the 'Grade' value is passed as parameter while executing the dynamic sql statement.

Ouput:

Dynamic SQL for Parameterized Queries

Uses of Dynamic SQL

Dynamic 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 allows to building of generic queries that can work with different tables, columns, and filtering conditions by using dynamic elements at runtime.
  • Users can build dynamic queries based on user inputs and application logic to generate dynamic data and reports.
  • Dynamic Filtering of Data can be done by creating dynamic SQL queries at runtime by user input for ‘WHERE’ clauses in a SQL query.
  • Using the dynamic SQL queries users can sort data displayed dynamically from user interface inputs.

Dynamic SQL and Security Risks

When 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.

Conclusion

Dynamic 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.



Similar Reads

Dynamic SQL and Temporary Tables in SQL Server
In SQL Server, creating and using Temp Tables using dynamic SQL is a good feature when we need to temporarily create tables at run time and delete automatically all within a session. They can be very useful when we need to store temporary data in a structured format and do data manipulation using Data Manipulation Language in SQL. In this article l
6 min read
Dynamic Table Name Variable in SQL Server
In SQL Server, the dynamic table name variable is used when the name of the table is not explicitly stated in a query but is set in a variable and used instead. This can be in situations where the user does not know or the executing code does not know the table name beforehand and is only determined at run time. Dynamic Table Variable UsageThe dyna
3 min read
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
Differences Between Selenium Standalone server and Selenium Client and WebDriver Server
In web application testing, Selenium has emerged as one of the most basic foundations, providing robust mechanisms for automating browsers. Among its suite, two elements stand out, which are: 'Selenium-server-standalone.jar' and 'Selenium Client and WebDriver'. Both 'Selenium-server-standalone.jar' and 'Selenium Client and WebDriver' are very impor
4 min read
SQL Server Universal Comparison Quantified Predicates (ANY, ALL, SOME)
Quantified Comparison Predicates are used to compare the value with every value in the set returned by the subquery. There are mainly two predicates available in SQL Server that are ALL and ANY/SOME. This clause is very useful when you have to compare two sets of values. These clauses are used for broader comparison just like OR and AND. Like, for
5 min read
Rank and Dense Rank in SQL Server
The RANK() and DENSE_RANK() functions are essential tools in SQL Server for assigning rankings to rows in a dataset based on specified criteria. RANK() functions assign a unique rank to each distinct row in the result set, with tied rows receiving the same rank and leaving gaps in subsequent ranks. For example, if two rows tie for first place, the
7 min read
UNPIVOT in SQL Server
In SQL Server, Unpivot is a relational operator that allows us to convert columns into rows in a table. It's far the reverse of the Pivot operation, which is used to transform rows into columns. Unpivot is typically used when we have a table with multiple columns, and we need to restructure the information to make it more to be had for evaluation o
2 min read
SQL Server UPDATE
SQL Server is a database engine. It works on the relational database management system (RDBMS) that allow programmer to create, manage, and manipulate data present on the relational database through their commands which is easy to learn and implement. UPDATE CommandThe UPDATE operation is a part of DML (Data Manipulation Language) in SQL Server whi
3 min read
SQL Server EXISTS
The EXISTS operator is used when we are dependent on another subquery which can be in the same table or a different table. When the subquery returns any rows the EXISTS operators return true otherwise false. EXISTS Operator simply checks whether the subquery returns any row. It gives true or False based on the existence of rows. In this article, yo
4 min read
SQL Server BIT Data Type
The BIT data type is used to store boolean values like 0, 1, or NULL. The SQL server doesn't have the data Boolean instead it has the data type BIT which has which stores the boolean value. The BIT data type is advantageous in terms of space optimization since each BIT data type takes on only 1 bit of storage, suppose their n columns in the table w
3 min read
three90RightbarBannerImg