Variables scope which are defined within a while block in stored procedures - SQl Server

后端 未结 8 867
没有蜡笔的小新
没有蜡笔的小新 2020-12-24 07:46

I\'ve come across a interesting scenario (at least for me) in a stored procedure. Would like to have experts opinion and thoughts on it.

DECLARE @loopcounter         


        
相关标签:
8条回答
  • 2020-12-24 08:20

    Try this for fun

    if 1 = 0
    begin
      -- will never happen
      declare @xx int
    end  
    else  
    begin
      set @xx = 1
    end  
    print @xx
    

    Apparently the declare code does not have to be executed. Only be declared before it is used.

    This don't work

    if 1 = 0
    begin
      -- will never happen
      set @xx = 1
    end  
    else  
    begin
      declare @xx int
    end  
    print @xx
    
    0 讨论(0)
  • 2020-12-24 08:20
    DECLARE @loopcounter INT
    SET @loopcounter=10
    
    WHILE @loopcounter > 0
    BEGIN
      DECLARE @insidevalue int
      IF (@loopcounter%2 = 0)
      begin
    
        set @insidevalue=@loopcounter
        PRINT 'Value_' + CAST(@insidevalue AS NVARCHAR) + '_'
      end
      ELSE
    
        PRINT 'Value_' + ' ' + '_'
        SET @loopcounter = @loopcounter - 1
    END
    
    0 讨论(0)
提交回复
热议问题