SQL Server variable scope in a stored procedure

后端 未结 4 407
猫巷女王i
猫巷女王i 2020-12-03 11:02

I would like to declare a variable within an if/else statement in a SQL Server stored procedure. I understand that this is fairly impossible because SQL Server doesn\'t do m

4条回答
  •  借酒劲吻你
    2020-12-03 11:20

    From books online:

    The scope of a variable is the range of Transact-SQL statements that can reference the variable. The scope of a variable lasts from the point it is declared until the end of the batch or stored procedure in which it is declared.

    However. Nothing keeps you from doing this:

    create procedure Foo as begin
    
    declare @bob int
    
    if exists (x)
    begin
        set @bob = 1
    end
    else
    begin
        set @bob = 2
    end
    
    end
    

提交回复
热议问题