我使用整数作为参数时收到错误

时间:2019-06-17 15:09:43

标签: sql sql-server stored-procedures

/ * 我在SQL存储过程中传递了一个整数作为参数,但是尽管声明了输入值,却收到了一个错误。

目的是在WHILE LOOP中使用传递给动态SQL中参数的值。

当通过参数将字符串值传递给动态SQL时,此方法可以正常工作,但使用整数值时,将返回错误消息:

第137条消息,第15级,状态2,第16行 必须声明标量变量“ @BUILDING_ID”

以下是我正在使用的实际代码:

* /

CREATE OR ALTER PROCEDURE dbo.USP_History_Building

     @BUILDING int

AS 

DECLARE @quarterStart int = 2
DECLARE @quarterEnd int = 1
DECLARE @yearStart int = 17
DECLARE @yearEnd int = 19

DECLARE @BUILDING_ID int

DECLARE @year int
DECLARE @quarter int

DECLARE @quarterForDbName nvarchar(4)
DECLARE @sqlStatement nvarchar(max)

SET @year = @yearStart
SET @quarter = @quarterStart
SET @sqlStatement = ''

SET  @BUILDING_ID = @BUILDING

WHILE @year <= @yearEnd
BEGIN
   WHILE ((@year < @yearEnd AND @quarter <= 4) OR (@year = @yearEnd AND @quarter <= @quarterEnd))
   BEGIN
    SET @quarterForDbName = 'Q' + CAST(@quarter AS nvarchar(1)) + CAST(@year AS nvarchar(2))
--  

        SET @sqlStatement = @sqlStatement + '


        SELECT '''+@quarterForDbName+''' AS Quarter, ADDRESS_POINT_ID, BUILDING_ID, ADDR_LINE_1, ADDR_LINE_2, ADDR_LINE_3, ADDR_LINE_4, ADDR_LINE_5, ADDR_LINE_6 FROM EDB_'+ @quarterForDbName +'.dbo.POSTAL_ADDRESS PA WHERE PA.BUILDING_ID = @BUILDING_ID'

      SET @quarter = @quarter + 1

   END
   SET @quarter = 1
   SET @year = @year + 1

END

PRINT @sqlStatement
EXEC (@sqlStatement)

/ 预期结果是大约8行,显示了前8个季度的6个地址字段。 /

2 个答案:

答案 0 :(得分:1)

'WHERE PA.BUILDING_ID =' + @BUILDING_ID

@BUILDING_ID ,因为它是变量,所以应该放在引号的另一侧。

答案 1 :(得分:0)

代替

'WHERE PA.BUILDING_ID = @BUILDING_ID'

您需要

'WHERE PA.BUILDING_ID =' + @BUILDING_ID

您还可以使用类似this

的参数
EXECUTE ('SELECT ProductID, Name   
    FROM AdventureWorks2012.Production.Product  
    WHERE ProductID = ? ', 952) AT SeattleSales;  
GO