SQL Server variable scope in a stored procedure

后端 未结 4 394
猫巷女王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:07

    No, SQL is pretty funny/weird like that

    Declare the variable before the if exists block of code

    so

    declare @bob int 
    set @bob = 2 
    
    if exists(x) 
    begin   
        set @bob = 1 
    end
    

    Now, take a look at these examples and try to guess what happens

    WHILE 1 = 2 --not true of course
    BEGIN
      DECLARE @VAR INT;
    END
    SET @VAR = 1;
    
    SELECT @VAR;
    

    This of course works, but it is not initialized every time

    DECLARE @loop INT
    SET @loop = 0
    
    WHILE @loop <=6
    BEGIN
            DECLARE @VAR INT
            SET @VAR = COALESCE(@VAR,0) + 1
            SET @loop = @loop +1
    END
    
    SELECT @VAR
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-03 11:24

    is there some reason why you can't do :

    declare @bob int 
    if exists(x) 
    begin   set @bob = 1 end 
    else 
    begin  set @bob = 2 end 
    
    0 讨论(0)
  • 2020-12-03 11:32

    You could resort to using dynamic SQL:

    if exists (x)
    begin
        exec sp_executesql N'
            declare @bob int
            set @bob = 1
        ';
    end
    else
    begin
        exec sp_executesql N'
            declare @bob int
            set @bob = 2
        ';
    end
    
    0 讨论(0)
提交回复
热议问题