Is it possible to run dynamic SQL scripts that include declaration of variables?
Example:
Important note: this example is only to demonstrate the mechanism I need to implement. The shown calculation is trivial for the sake of simplicity.
I need to return the minimal value between 4 passed values so, programmatically, I create a string that contains the following code:
DECLARE @_1 INT = 12 ;
DECLARE @_2 INT = 22 ;
DECLARE @_3 INT = 32 ;
DECLARE @_4 INT = 42 ;
DECLARE @_Min = NULL ;
SET @_Min = @_1 ;
IF (@_2 < @_Min) SET @_Min = @_2 ;
IF (@_3 < @_Min) SET @_Min = @_3 ;
IF (@_4 < @_Min) SET @_Min = @_4 ;
SELECT @_Min ;
Again, all this is contained in a string variable (say @_Command
).
To execute this and get the result of the calculation, I would be running the following command:
EXECUTE sp_executesql @_l_Command ,
N'@_l_Result FLOAT OUTPUT' ,
@_l_Result = @_l_Result OUTPUT ;
When running it, I get an error message stating:
Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'DECLARE'.
Obviously I'm doing something syntactically wrong but cannot figure out what it could be.