What is Dynamic SQL?
Dynamic SQL is about creating and running SQL Statements at run-time. We can store a SQL statement inside a variable and execute that statement.
It is for the most part used to compose broadly useful and adaptable projects where the SQL Statements will be made and executed at run-time in light of the prerequisite.
Why do we need Dynamic SQL?
Dynamic SQL is very helpful to dynamically set the filters, columns, and table names.
Downsides of Dynamic SQL
It's riskier because the SQL statements aren't parsed until runtime, so it's more difficult to catch simple syntax errors. Also, many attempts at dynamic SQL run into performance problems, and the complexity of simply writing dynamic SQL gives a negative impression on dynamic SQL.
How we Achieve Dynamic SQL?
We will achieve the Dynamic SQL by String concatenation and exec statement in SQL.
String concatenation means appending different strings together in strings that are the varchar data type.
Declare a varchar variable and append the string checking conditions and use EXEC Statement to execute that varchar variable.
Simple Dynamic SQ
Dynamic SQL Using Table Name as Dynamic
Dynamic SQL Using Column Name as Dynamic
Dynamic SQL Using Table Using Filters
Note: In the above examples, we are appending values in the varchar variable so another type of variable needs to be converted as varchar. For varchar variables mention that variable in Triple Quotes like this '''+@designation+''' because in SQL we give string in between quotes.
Example
To execute the Dynamic SQL use
To view how the dynamically generated query looks like use
Summary
In this article, we have learned the basics of Dynamic SQL.