You cannot concatenate int into string. Instead:
SET @sql = N'DECLARE @Rt INT; SET @Rt = ' + @RowTo;
You need:
SET @sql = N'DECLARE @Rt INT; SET @Rt = ' + CONVERT(VARCHAR(12), @RowTo);
To illustrate what is 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 sp_executeSQL @sql;
To build this into a string (even if it ends up being a number), I need to convert it. But, as you can see, the number is still treated as a number when it is executed. Answer: 25, right?
In your case, you do not need to re-declare @Rt, etc. inside the @sql line, you just need to say:
SET @sql = @sql + ' WHERE RowNum BETWEEN ' + CONVERT(VARCHAR(12), @RowFrom) + ' AND ' + CONVERT(VARCHAR(12), @RowTo);
Although it would be better to have the correct parameterization, for example
SET @sql = @sql + ' WHERE RowNum BETWEEN @RowFrom AND @RowTo;'; EXEC sp_executesql @sql, N'@RowFrom INT, @RowTo INT', @RowFrom, @RowTo;
Aaron Bertrand Aug 24 2018-11-21T00: 00Z
source share