为什么这段代码给出一行 NULL
值而不是错误消息 必须声明标量变量“@i”。
。为什么 Microsoft 在 t-sql 中使用这种行为?
if 1 = 0
begin
declare @i int = 1;
end;
select @i;
最佳答案
来自 MSDN :
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.
因此在您的示例中,@i
变量的范围是定义它们的批处理或过程。
所以下一个查询:-
if 1 = 0
begin
declare @i int = 1
end
else
begin
declare @i int = 3
end
select @i
正在检索下一个错误:-
The variable name '@i' has already been declared. Variable names must be unique within a query batch or stored procedure.
但您的查询没有。
更新
Microsoft 表示他们不会解决此问题:-
Make it possible to declare variables that are only visible within a block.
关于sql-server - 访问未声明的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41329125/