Trouble with Global Input Parameters and SQL Execution
In a stored procedure that compiles an SQL query with T-SQL and executes it using EXEC (@sqlstatement), you may encounter an error stating "Must declare the scalar variable "@RowFrom"." when attempting to use global input parameters @RowFrom and @RowTo within the @sqlstatement variable.
Understanding the Issue
The error occurs because the parameters @RowFrom and @RowTo are not recognized within the @sqlstatement string. This is because SQL strings cannot directly access global variables without explicit declaration.
Solution: Converting Int to String or Using Proper Parameterization
There are two approaches to resolve this issue:
SET @sql = N'DECLARE @Rt int; SET @Rt = ' + CONVERT(VARCHAR(12), @RowTo);
SET @sql = @sql + ' WHERE RowNum BETWEEN @RowFrom AND @RowTo;'; EXEC sys.sp_executesql @sql, N'@RowFrom int, @RowTo int', @RowFrom, @RowTo;
Consideration for Modern Versions
In modern versions of SQL, you can use the CONCAT function for string concatenation:
SET @sql = CONCAT(N'SELECT ', @RowTo, ' * 5');
However, it's recommended to use proper parameterization to prevent SQL injection vulnerabilities.
The above is the detailed content of How to Handle Global Input Parameters in T-SQL Stored Procedures When Executing Dynamic SQL?. For more information, please follow other related articles on the PHP Chinese website!