SQL Server:必须声明标量变量

问题描述 投票:0回答:1

我需要将全局变量声明为计数器

DECLARE @counter int
SET @counter = 0;

然后使用存储过程,但是它总是告诉我必须将@counter声明为标量变量

CREATE OR ALTER PROCEDURE proc_counter_type 
     @type NVARCHAR(15), 
     @dateFirst DATE,
     @dateSecond DATE
AS
    SELECT @counter = COUNT(title_id)
    FROM books
    WHERE type = @type AND (datum BETWEEN @dateFirst AND @dateSecond)
sql sql-server stored-procedures ssms
1个回答
1
投票

您需要将@Counter添加为OUTPUT参数:

CREATE OR ALTER PROCEDURE proc_counter_type @type nvarchar(15), @dateFirst date, @dateSecond date, @Counter int OUTPUT 
AS
BEGIN
    SELECT @counter = COUNT(title_id)
    FROM books
    WHERE type = @type
      AND (datum BETWEEN @dateFirst AND @dateSecond);
END;

然后您以以下方式执行SP:

DECLARE @counter int;
--Other Params
EXEC proc_counter_type, @Type, @dateFirst, @dateSecond, @Counter OUTPUT;

PRINT @Counter;
© www.soinside.com 2019 - 2024. All rights reserved.