The other day during Comprehensive Database Performance Health Check, I was asked if there is a way to store results of dynamic SQL into a variable. This is a very popular question and let us see the answer to this question in this blog post.
For example here is the dynamic SQL which I am executing with the help of sp_executeSQL. When you run the procedure, you get the necessary results. In our case, we are seeing a result string as a Marketing which is the name of the department with ID = 4.
DECLARE @sqlCommand NVARCHAR(4000) DECLARE @ID INT SET @ID = 4 SET @sqlCommand = 'SELECT [Name] FROM [AdventureWorks2014].[HumanResources].[Department] WHERE DepartmentID = @ID' EXEC sp_executesql @sqlCommand, N'@ID INT', @ID = @ID
Now the question is how to get the value of the column [Name] into a variable.
Here is the very easy trick for the same. Here is the script which declares additional parameter which is Name and returns value into it.
DECLARE @sqlCommand NVARCHAR(4000) DECLARE @ID INT DECLARE @Name NVARCHAR(100) SET @ID = 4 SET @sqlCommand = 'SELECT @Name = [Name] FROM [AdventureWorks2014].[HumanResources].[Department] WHERE DepartmentID = @ID' EXEC sp_executesql @sqlCommand, N'@ID INT, @Name NVARCHAR(100) OUTPUT', @ID = @ID, @Name = @Name OUTPUT SELECT @Name ReturnedName
You can use this script and example as a template for your need where you want to run dynamic SQL and store the result of it into a variable.
If you have any such script, I request you to share the same with me and I will publish it with due credit to you. Please always use sp_executesql instead of just EXEC to run your dynamic SQL.
Reference:Â Pinal Dave (https://darkslategrey-bat-805937.hostingersite.com)