必须在sql过程中声明标量变量

时间:2012-12-14 09:18:52

标签: sql-server stored-procedures

请问下面的程序声明有什么问题

    DECLARE  @result int 
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    set @result = (select COUNT(*) from populate)

    if (@result > 1)
    Begin
        insert into populate (brch, terminal_id) values(@branch, @atmid)
    end

    SET ANSI_NULLS ON
    GO
     SET QUOTED_IDENTIFIER ON
    GO

    CREATE PROCEDURE insertion @id varchar(50), @brch varchar(50)
    -- Add the parameters for the stored procedure here

   AS
    BEGIN
   DECLARE  @result int 
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    set @result  = (COUNT(*) from populate)

    if (@result > 1)
    Begin
        insert into populate (brch, terminal_id) values(@id, @brch)
    end
    END
    GO

3 个答案:

答案 0 :(得分:1)

通过首先发布一段提供错误Msg 137, Level 15, State 2, Line 11 Must declare the scalar variable "@branch".的代码然后添加一个提供错误Msg 156, Level 15, State 1, Procedure insertion, Line 13 Incorrect syntax near the keyword 'from'.

的完整过程,您似乎感到困惑。

请确保您发布正在使用的真实代码以及完整的错误消息,否则人们无法帮助您。

无论如何,我忽略了代码片段并只查看了该过程,正如ABFORCE所说,问题在于您填充@result,因为您的语法错误。此过程代码在SQL Server 2008中无错误地解析:

   CREATE PROCEDURE insertion @id varchar(50), @brch varchar(50)
    -- Add the parameters for the stored procedure here

   AS
    BEGIN
   DECLARE  @result int 
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    select @result  = COUNT(*) from populate

    if (@result > 1)
    Begin
        insert into populate (brch, terminal_id) values(@id, @brch)
    end
    END
    GO

您可能需要查看assigning values to variablesSET关键字的文档。

答案 1 :(得分:0)

正如错误消息中所述,问题是@branch@atmid在使用其值之前未在任何地方提及。

您已声明@resultset它的值,因此您需要对@branch@atmid执行相同的操作,系统无法为您分配值

答案 2 :(得分:0)

试试这个

select @result =COUNT(*) from populate