开发者

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

When I write

DECLA开发者_StackOverflowRE @x INT

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


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


IF you try to access a variable that has not yet been defined, the T-SQL Script will give you an error telling you the variable isn't defined.

Msg 137, Level 15, State 2, Line 5 Must declare the scalar variable "@x".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜