Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Deve dichiarare la variabile scalare

Non puoi concatenare un int a una stringa. Invece di:

SET @sql = N'DECLARE @Rt int; SET @Rt = ' + @RowTo;

Hai bisogno di:

SET @sql = N'DECLARE @Rt int; SET @Rt = ' + CONVERT(VARCHAR(12), @RowTo);

Per aiutare a illustrare cosa sta succedendo qui. Diciamo @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;

Per costruirlo in una stringa (anche se alla fine sarà un numero), devo convertirlo. Ma come puoi vedere, il numero viene comunque trattato come un numero quando viene eseguito. La risposta è 25, giusto?

Nel tuo caso puoi usare una parametrizzazione adeguata piuttosto che usare la concatenazione che, se prendi questa abitudine, ti esporrai a SQL injection a un certo punto (vedi questo e questo:

SET @sql = @sql + ' WHERE RowNum BETWEEN @RowFrom AND @RowTo;';

EXEC sys.sp_executesql @sql,
  N'@RowFrom int, @RowTo int',
  @RowFrom, @RowTo;