Today we will learn on how to dynamic SQL query by passing a dynamic parameter
Scenario: Suppose you want to fetch data from multiple servers and databases using one common SQL statement (change database and server name dynamically in one query). To achieve this, we have to user dynamic query in SQL.
Steps:
- Create two variables:
- Servername
- Databasename
- Declare the third variable (@SQL) as nvarchar(max) that will hold our SQL query.
- use single quotes and '+' sign to parse the variables
- To test the query, use "select @sql".
- It will give you the final SQL statement formed after parsing the dynamic parameters
- Once you are satisfied with the result of SQL, change the "select @SQL" to "execute (@SQL)"
No comments:
Post a Comment