简体   繁体   中英

SQL Server : Must declare the scalar variable

I need to declare globally variable as counter

DECLARE @counter int
SET @counter = 0;

And then use a stored procedure, but it always tells me that @counter must be declared as scalar variable

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)

You need to add @Counter as an OUTPUT parameter:

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;

Then you execute the SP as:

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

PRINT @Counter;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM