articles

Home / DeveloperSection / Articles / Explain the Dynamic SQL Query with example in SQL Server.

Explain the Dynamic SQL Query with example in SQL Server.

Explain the Dynamic SQL Query with example in SQL Server.

Ashutosh Kumar Verma 207 10-Jul-2024

Dynamic Qurey in SQL Server

Dynamic query refers to SQL statements that are created and executed dynamically at runtime, rather than hardcoded into a program or stored procedure. This allows for flexible and customizable queries, where the query structure or conditions can change based on variables or circumstances.

Here is an example of how to use Dynamic query in SQL Server.

Suppose we have a table called Employees with columns EmpId,EmpName, Gender,  Salary, and DepartmentId

Here is the simple dynamic Query Created in the SQL Server,

DECLARE @Search NVARCHAR(100) = 'Female';DECLARE @SQL NVARCHAR(MAX);SET @SQL = 'SELECT * FROM Employees WHERE Gender = '''+@Search+''' '-- execute the above dynamic queryEXEC(@SQL);

Example-

Explain the Dynamic SQL Query with example in SQL Server.

In the example above-

there are three ‘ ’ are used with the @search variable, it is used for escaping the‘ ’ in dynamic query.

 

If you want to create a stored procedure that fetches employee information based on different criteria passed as parameters.

USE MyCollegeDbGOCREATE PROCEDURE GetEmployees (@EmpName NVARCHAR(50) = '')ASBEGINSET NOCOUNT ON;DECLARE @SQL NVARCHAR(MAX);SET @SQL = 'SELECT * FROM Employees WHERE EmpName LIKE ''%'+@EmpName+ '%'' 'PRINT @SQL-- execute the above dynamic queryEXEC(@SQL);SET NOCOUNT OFF;END

 

Execute the procedure- 

Explain the Dynamic SQL Query with example in SQL Server.

Explanation-

Procedure Definition
The GetEmployees option accepts optional parameters: @EmpName.

Dynamic SQL Construction (@sql)
We start with a base SQL query (SELECT … FROM Employees WHERE condition) and dynamically add conditions based on availableinput parameters.

Conditionals
If @EmpNameis provided, we add a condition to filter by Employee name

Execution (sp_executesql)
Finally, the concatenated SQL string (@sql) is executed using sp_executesql.
We pass parameter ( @EmpName) to sp_executesql using the format on the parameter.


When using dynamic SQL, it is important to consider security implications (such as SQL injection vulnerabilities) and performance due to query plan caching. Adoption of appropriate testing and investment policies is essential to mitigating these risks.

 

Also, Read: Explain the SQL triggers and their uses


Updated 11-Jul-2024
Hi! This is Ashutosh Kumar Verma. I am a software developer at MindStick Software Pvt Ltd since 2021. I have added some new and interesting features to the MindStick website like a story section, audio section, and merge profile feature on MindStick subdomains, etc. I love coding and I have good knowledge of SQL Database.

Leave Comment

Comments

Liked By