解决此错误的错误(必须声明标量变量“ @totalproduct”。)

时间:2020-06-11 07:38:51

标签: sql sql-server

create proc my_procedure2
    @shopname varchar(50),
    @totalproduct varchar(225) output
as
begin
    select @totalproduct  = 'Total Product of' + @shopname + 'is' + count(p.p_id)
    from product p
    join Shop_products s on p.p_id = s.p_id
    join shop a on a.s_id = s.s_id
    where a.s_name = @shopname
end

declare @totalproduct varchar(225)

exec my_procedure2 'Kiran Electronics' ,@totalproduct = @totalproduct  output

这根本无法正常工作,因为会得到一些标量值的错误。

必须声明标量变量“ @totalproduct”。

2 个答案:

答案 0 :(得分:1)

在创建和执行之间添加一个简单的GO会将它们分为不同的批次并消除问题。

create proc my_procedure2
    @shopname varchar(50),
    @totalproduct varchar(225) output
as
begin
    select @totalproduct  = 'Total Product of' + @shopname + 'is' + count(p.p_id)
    from product p
    join Shop_products s on p.p_id = s.p_id
    join shop a on a.s_id = s.s_id
    where a.s_name = @shopname
end

GO

declare @totalproduct varchar(225)

exec my_procedure2 'Kiran Electronics' ,@totalproduct = @totalproduct  output

它在SQL Server 2014上对我有效。

答案 1 :(得分:1)

BEGINEND不是批处理分隔符。当您CREATE使用存储过程时,SP的定义中将使用批次的整个 entirety (我的意思是 entirety )。甚至在CREATE之前也没有评论。

采取类似以下的方式:

--Here is a line comment

/* Here's a block comment.
This is an answer by Larnu
on the website Stackoverflow.com
Enjoy!
*/

CREATE PROC dbo.MyProc @MyParam int AS
BEGIN

    SELECT @MyParam * 10 AS YourResult;

END;

EXEC dbo.MyProc 10;

--Thank you for reading

现在,让我们用sys.sp_helptext看一下该过程的定义:

EXEC sys.sp_helptext N'dbo.MyProc';
text
-------------------------------------
--Here is a line comment

/* Here's a block comment.
This is an answer my larnu
on the website Stackoverflow.com
     Enjoy!
*/

CREATE PROC dbo.MyProc @MyParam int AS
BEGIN

    SELECT @MyParam * 10 AS YourResult;

END;

EXEC dbo.MyProc 10;

--Thank you for reading

如您所见,批次中的所有都在SP的定义中。

如果要创建一个过程,然后调用它,则需要分开批次。在与SQLCMD,SSMS,ADS的接口中,这就是GO实用程序(GO 不是 Transact-SQL运算符)。如果我们DROP先前的过程(DROP PROC dbo.MyProc;),然后在GO后面加上END,您将得到以下行为:

--Here is a line comment

/* Here's a block comment.
This is an answer my larnu
on the website Stackoverflow.com
     Enjoy!
*/

CREATE PROC dbo.MyProc @MyParam int AS
BEGIN

    SELECT @MyParam * 10 AS YourResult;

END;
GO
EXEC dbo.MyProc 10;

--Thank you for reading

首先,现在请注意,在运行这两个批处理时,您将得到结果100。另外,如果您使用sys.sp_helptext,则EXEC命令不在底部。