I am using SQL Server 2008 and I have a variable @sqlFinal which is of type Varchar(500).
I fill the variable as the stored procedure runs. I want to dynamically return what is in the string to show the results
SELECT @sqlFinal = 'SELECT @Error_Return AS Final_Report'
--PRINT @sqlFinal
EXEC (@sqlFinal)
But I get the following error
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable “@Error_Return”.
I am assuming that @Error_Return is in the same scope as @SqlFinal?
If you just need to return the contents of @Error_Return, you can just execute this line:
… making it a static SQL line rather than a dynamic one.
But if that’s not acceptable, you may have to use sp_executeSQL instead. This allows you to pass variables to the line you’re executing.