How to check if a variable is already declared (T-SQL)?

前端 未结 2 770
感动是毒
感动是毒 2021-01-07 22:11

When I write

DECLARE @x INT

Is there a way to check whether the variable @x has already been declared or not?

2条回答
  •  星月不相逢
    2021-01-07 22:51

    No.
    The declaration of variables in tsql does not follow the code path and use scope like perhaps other languages does.

    This code shows that @xx exists but is unassigned even though the declaration was never executed.

    if 1 = 0 
    begin
      declare @xx int = 10
    end
    else
    begin
      declare @yy int = 20
    end
    
    print coalesce(@xx, -100)
    print coalesce(@yy, -200)
    

    Result

    -100
    20
    

提交回复
热议问题