@RowFrom int
@RowTo int
are both Global Input Params for the Stored Procedure, and since I am compiling the SQL query inside the Stored Procedure with T-SQL then using Exec(@sqlstatement)
at the end of the stored procedure to show the result, it gives me this error when I try to use the @RowFrom
or @RowTo
inside the @sqlstatement
variable that is executed.. it works fine otherwise.. please help.
"Must declare the scalar variable "@RowFrom"."
Also, I tried including the following in the @sqlstatement
variable:
'Declare @Rt int'
'SET @Rt = ' + @RowTo
but @RowTo
still doesn't pass its value to @Rt
and generates an error.
You can't concatenate an int to a string. Instead of:
SET @sql = N'DECLARE @Rt int; SET @Rt = ' + @RowTo;
You need:
SET @sql = N'DECLARE @Rt int; SET @Rt = ' + CONVERT(VARCHAR(12), @RowTo);
To help illustrate what's happening here. Let's say @RowTo = 5.
DECLARE @RowTo int;
SET @RowTo = 5;
DECLARE @sql nvarchar(max);
SET @sql = N'SELECT ' + CONVERT(varchar(12), @RowTo) + ' * 5';
EXEC sys.sp_executesql @sql;
In order to build that into a string (even if ultimately it will be a number), I need to convert it. But as you can see, the number is still treated as a number when it's executed. The answer is 25, right?
In modern versions you can use CONCAT()
to avoid handling NULL
or conversion issues:
SET @sql = CONCAT(N'SELECT ', @RowTo, ' * 5');
But in your case you should use proper parameterization rather than concatenation. If you keep using concatenation, you will expose yourself to SQL injection at some point (see this and this):
SET @sql = @sql + ' WHERE RowNum BETWEEN @RowFrom AND @RowTo;';
EXEC sys.sp_executesql @sql,
N'@RowFrom int, @RowTo int',
@RowFrom, @RowTo;