为什么即使条件评估为假,也会在 IF 语句中创建变量声明? [英] Why is variable declared inside IF statement created even when condition evaluates to false?

查看:28
本文介绍了为什么即使条件评估为假,也会在 IF 语句中创建变量声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为@A 从来没有被声明过,sql server 应该抛出一个错误,但它没有.这是为什么?

Since @A is never declared, sql server should throw an error, but it doesn’t. Why is that?

DECLARE @i int = 1;
IF @i > 10
BEGIN
  DECLARE @A int = 100;
END

PRINT @A; // doesn't return any result

谢谢

推荐答案

SQL Server 没有块级变量作用域.

SQL Server does not have block level variable scoping.

按批次/存储过程等

来自 MSDN(我的粗体)

变量的作用域是范围的 Transact-SQL 语句,可以引用变量.范围变量从它所在的点开始声明到批次结束或存储过程声明.

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.

这篇关于为什么即使条件评估为假,也会在 IF 语句中创建变量声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆