Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • SQL Server - Get Started
  • Install SQL Server
  • SQL Server Management Studio
  • SQL Server - Windows Authentication
  • SQL Server - Authentication
  • SQL Server - Create New User
  • SQL Server - GRANT/REVOKE Permissions to User
  • SQL Server - Data Types
  • SQL Server - Naming Conventions
  • SQL Server - CREATE Database
  • SQL Server - CREATE Table
  • Add Columns
  • Identity Column
  • Rename Column, Table
  • Drop Columns
  • SQL Server - Schema
  • SQL Server - Tables Relations
  • SQL Server - Primary Keys
  • Modify/Delete Primary Keys
  • SQL Server - Foreign Keys
  • Modify/Delete Foreign Keys
  • SQL Server - Check Constraints
  • SQL Server - Unique Constraints
  • SQL Server - Views
  • Modify/Delete Views
  • SQL Server - Functions
  • SQL Server - Stored Procedures
  • Stored Procedure Parameters
  • SQL Server - Indexes
  • Non-clustered Indexes
  • Modify/Delete Indexes
  • SQL Server - Triggers
  • DDL Triggers
  • LOGON Triggers
  • Enable/Disable Triggers
  • Modify/Delete Triggers
  • SQL Server - Sequence
  • SQL Server - Synonyms
  • SQL Server - IF ELSE Statement
  • SQL Server - Loops
  • SQL Server - Insert Data
  • SQL Server - Update Data
  • SQL Server - Delete Data
  • SQL Server - Select Query
  • WHERE Clause
  • GROUP BY Clause
  • HAVING Clause
  • ORDER BY Clause
  • SQL Server - Inner Join
  • Left Join
  • Right Join
  • Full Join
  • Self Join
  • Dynamic SQL
  • Built-in Functions
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Dynamic SQL in SQL Server

Dynamic SQL is a programming technique where you build SQL query as a string and execute it dynamically at runtime. It lets you build the general-purpose query on the fly using variables, based on the requirements of the application. This makes a dynamic SQL more flexible as it is not hardcoded.

For example, the following is a dynamic SQL.

Example: Dynamic SQL
DECLARE @sql nvarchar(max) --declare variable
DECLARE @empId nvarchar(max) --declare variable for parameter

set @empId = '5' --assign value to parameter variable
set @sql = 'SELECT * FROM EMPLOYEE WHERE EMPID =' + @empId --build query string with parameter

exec(@sql) --execute sql query

In the above example, we first declare variables, @sql for SQL query and @empId for the parameter. Then, @empId = '5' statement assigns value to a variable. The set @sql = statement builds the SQL query as a string and appends parameter variable using + operator. Finally, exec(@sql) executes the @sql string and returns the result.

The dynamic SQL query string can be executed using EXEC or EXECUTE command or using the sp_executesql stored procedure.

Example: Execute Dynamic SQL using sp_executesql
DECLARE @sql nvarchar(max) --declare variable
DECLARE @empId nvarchar(max) --declare variable for parameter

set @empId = '5' --assign value to parameter variable
set @sql = 'SELECT * FROM EMPLOYEE WHERE EMPID =' + @empId --build query string with parameter
exec sp_executesql @sql

You can also build and execute SQL query string by directly passing the SQL query string to sp_executesql stored procedure, as shown below.

Example: Build and Execute Dynamic SQL
exec sp_executesql N'SELECT * FROM EMPLOYEE WHERE EMPID = @empId', 
N'@empid nvarchar(50)', @empId = '5'

The above would return the same result.

The following is the syntax to build and execute dynamic SQL using sp_executesql.

Syntax
sp_executesql N'SQL query', N'@param1 data_type', @param1 = 'value1'

Dynamic SQL for DML statements

You can also build and execute dynamic SQL for DML statements like update and delete. The following example shows how to build the dynamic SQL for the UPDATE statement.

Example: Dynamic DML Statements
--declare variables
DECLARE @dynamicSQL nvarchar(max),
        @sal float,
        @empid int

-- assign values
set @sal = 53000 
set @empid = 5

-- declare string variables for parameters
DECLARE @salstr nvarchar(30),
        @empstr varchar(1000)

-- cast float and int parameters to string
SET @salstr  = CAST(@sal as nvarchar(30));
SET @empstr  = CAST(@empid as nvarchar(1000));

-- build dynamic upate statement
SET @sql = 'update Employee SET Salary = ' + @salstr +
            'WHERE EmpId = ' +  @empstr 

--execute dynamic statement
EXEC(@sql)

Dynamic SQL is about building SQL statements as a string and all variables are cast as string (nvarchar) variables. The above dynamic SQL updates the salary column of the Employee table in the database. We pass two variables, @sal and @empid to the UPDATE SQL string.@sal is a float data type and @empid is an integer data type. They are converted to string variables using the CAST statement before passing them to the SQL string.

Dynamic SQL in the Stored Procedure

You can convert the above dynamic SQL into a stored procedure as shown below. The stored procedure accepts two parameters, @sal and @empid

Example:
CREATE PROCEDURE uspDynamiDMLsql(@sal float, @empid int)
AS
BEGIN
	DECLARE @dynamicSQL nvarchar(max),
            @salstr nvarchar(30),
            @empstr varchar(1000)

        -- cast float and int parameters to string
        SET @salstr  = CAST(@sal as nvarchar(30));
        SET @empstr  = CAST(@empid as nvarchar(1000));

        -- build dynamic upate statement
        SET @sql = 'update Employee SET Salary = ' + @salstr +
                    'WHERE EmpId = ' +  @empstr 

        --execute dynamic statement
        EXEC(@sql)
END

You can execute the above stored procedure as follows:

Example: Execute Stored Procedure
EXEC uspDynamiDMLsql 53000, 5

Dynamic SQL for a DDL statement

Let's take the example of deleting a table using the DROP statement in the dynamic SQL.

In the following example, the table name is a variable that is passed to the SQL statement. This dynamic SQL is flexible and can be reused. It can be used to delete any table as it is input as a parameter and not hardcoded.

Example: Dynamic SQL for DDL Statements
DECLARE @sql nvarchar(max),
        @tablename nvarchar(50)

SET @tablename = 'dbo.TableLog'
SET @sql = N'DROP TABLE ' + @tablename

EXEC(@sql)

Advantages of Using Dynamic SQL

  • Dynamic SQL is flexible and can be reused by using parameters in building the query.
  • Performance is improved as a better execution plan is generated.

Disadvantages of Using Dynamic SQL

  • Hard to debug.
  • Error management is difficult and unreliable.
  • It is vulnerable to SQL injection and can cause security concerns.
  • Dynamic SQL is slower than static SQL as SQL Server must generate an execution plan every time at runtime.
  • Dynamic SQL requires the users to have direct access permission on all accessed database objects like tables and views.
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.