sp_executesql in Transact-SQL
Why we want to use sp_executesql
One use case for this stored procedure is when we need to do parameterized linked query using OPENQUERY. I could have constructed a string with the parameter decorated by some special characters such as {{Parameter}} (This resembles the handlebar a lot, or AngularJS) and use EXEC to execute the query. However, a fundamental flaw with that approach is that I will not be able to return a value since the query cannot be parameterized. With the help of sp_executesql, we are able to provide input and output parameters
How to use
Please take a look at the following query
1 | DECLARE @LinkedServer NVARCHAR(100) = 'v2', |
According to the Official Document, the query has the following format
1 | sp_executesql [ @stmt = ] statement |
Simply speaking, it looks like
1 | EXECUTE sp_executesql |
In the code sample, we have one output parameter @TotalCountOut, after return, we can check the value of @TotalCountOut