Sql-Server

儲存過程錯誤“必須聲明標量變數”

  • June 21, 2019

我正在嘗試創建一個包含動態 SQL 的儲存過程。proc 接收 5 個變數,其中 3 個是列和欄位的名稱,另外 2 個用於 OFFSET 和 FETCH NEXT 部分。我在最後兩個變數上不斷收到此錯誤:

Msg 137, Level 15, State 2, Line 34 必須聲明標量變數“@numOfOffset”。Msg 137, Level 15, State 2, Line 34 必須聲明標量變數“@numOfRows”。

我會很感激一些幫助,請

IF (SELECT 1 FROM sys.procedures WHERE [name] = 'sp_targil1') = 1
   DROP PROCEDURE sp_targil1;
GO

CREATE PROCEDURE sp_targil1 (@tableName varchar(30), @fieldNameAggBy varchar(30), @fieldNameToAggOn varchar(30)
   ,  @numOfOffset int, @numOfRows int
   )
AS
BEGIN
   DECLARE @query1 varchar(500)
   DECLARE @qaeryMain varchar(500)
   DECLARE @maxNumberOfRows int

   SET @qaeryMain = 
   '
   SELECT ' + @fieldNameAggBy + ', SUM(' + @fieldNameToAggOn + ') AS ' + @fieldNameToAggOn + '_Sum_By_' + @fieldNameAggBy +
   ' FROM ' + @tableName +
   ' GROUP BY ' + @fieldNameAggBy + 
   ' ORDER BY SUM(' + @fieldNameToAggOn + ') DESC OFFSET @numOfOffset - 1 ROWS FETCH NEXT @numOfRows ROWS ONLY'
   PRINT @qaeryMain
   EXECUTE (@qaeryMain)
END

您沒有在 Dynamic SQL 語句的上下文中聲明任何一個@numOfOffset@numOfRows變數。如果您複製PRINT @qaeryMain語句的輸出,您會注意到明顯缺少任何DECLARE語句,這就是您收到錯誤的原因。

如果您只是將程式碼更改為以下內容,它應該可以解決您的問題,因為它將在您的 DSQL 語句中指定文字而不是未定義的變數。

IF (SELECT 1 FROM sys.procedures WHERE [name] = 'sp_targil1') = 1
   DROP PROCEDURE sp_targil1;
GO

CREATE PROCEDURE sp_targil1 (@tableName varchar(30), @fieldNameAggBy varchar(30), @fieldNameToAggOn varchar(30)
   ,  @numOfOffset int, @numOfRows int
   )
AS
BEGIN
   DECLARE @query1 varchar(500)
   DECLARE @qaeryMain varchar(500)
   DECLARE @maxNumberOfRows int

   SET @qaeryMain = 
   '
   SELECT ' + @fieldNameAggBy + ', SUM(' + @fieldNameToAggOn + ') AS ' + @fieldNameToAggOn + '_Sum_By_' + @fieldNameAggBy +
   ' FROM ' + @tableName +
   ' GROUP BY ' + @fieldNameAggBy + 
   ' ORDER BY SUM(' + @fieldNameToAggOn + ') DESC OFFSET ' + CAST(@numOfOffset AS VARHCAR(50)) + ' - 1 ROWS FETCH NEXT ' + CAST(@numOfRowsAS VARHCAR(50)) + ' ROWS ONLY'
   PRINT @qaeryMain
   EXECUTE (@qaeryMain)
END

引用自:https://dba.stackexchange.com/questions/241128