Home >Database >Mysql Tutorial >How to Fix 'Must declare the scalar variable '@RowFrom'' Error When Using Global Input Parameters in Stored Procedures?
Addressing Compilation Error with "@RowFrom" and "@RowTo" Global Input Parameters
In a stored procedure, declaring global input parameters is necessary for using them within the procedure. However, when executing a compiled SQL query inside the stored procedure using "Exec(@sqlstatement)," the error "Must declare the scalar variable '@RowFrom'" may arise if the "@RowFrom" or "@RowTo" input parameters are not properly declared or used.
The provided error message indicates that the "@RowFrom" variable has not been declared. To resolve this, explicitly declare "@RowFrom" and "@RowTo" as scalar variables inside the stored procedure before referencing them in the SQL query.
Additionally, when trying to assign the value of "@RowTo" to a new variable using concatenation, ensure that the variable type is converted appropriately. Instead of the incorrect syntax
SET @Rt = ' + @RowTo
use the correct syntax to cast "@RowTo" to a string:
SET @Rt = ' + CONVERT(VARCHAR(12), @RowTo)
Modern versions of SQL Server support the CONCAT() function, which simplifies these operations:
SET @sql = N'SELECT ' + CONVERT(varchar(12), @RowTo) + ' * 5';
However, for better security against SQL injection, it is recommended to use parameterized SQL statements instead of concatenation. This involves passing input parameters to the SQL query explicitly, as in the following example:
SET @sql = @sql + ' WHERE RowNum BETWEEN @RowFrom AND @RowTo;'; EXEC sys.sp_executesql @sql, N'@RowFrom int, @RowTo int', @RowFrom, @RowTo;
The above is the detailed content of How to Fix 'Must declare the scalar variable '@RowFrom'' Error When Using Global Input Parameters in Stored Procedures?. For more information, please follow other related articles on the PHP Chinese website!