sql-server - 访问未声明的变量

标签 sql-server tsql

为什么这段代码给出一行 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/

相关文章:

sql - 如何从任何 SQL 表中删除所有空行

sql-server - 如何从 2 列的 UNION 中获取 TOP 1 值?

sql - 我应该在 T-SQL 中使用 != 或 <> 表示不等于吗?

sql - 更新连接导致错误 : Subquery returned more than 1 value

sql - 如何在 SQL Server 中散列表的列?

sql - 如何在集成服务目录中启用创建目录选项?

sql-server - 有没有办法确保字段的内容是 NULL 或 UNIQUE

sql-server - SQL Server : split a column into multiple columns (tabular format)

sql-server - 一个简单的选择语句花费太多时间

只有两列的 SQL Pivot