IF 语句未按预期引发错误
假设 @Ref <>第一个条件为 0。因此,我的代码将无法达到
@XYZ
(第 2 行) 的声明。
我认为它必须在第二个 IF
中引发错误,因为未声明 @XZY
。
但令我惊讶的是没有出现任何错误。
IF @Ref = 0
BEGIN
DECLARE @XYZ int
SELECT @XYZ = RISKGROUP
FROM POLCONT WITH (NOLOCK, NOWAIT)
WHERE CONT = 555
END
IF @RISKGROUP <> @XYZ
BEGIN
-- do something ...
END
例如。
在 python 中,它会引发此错误:
错误:赋值前引用了局部变量“XYZ”
Assume @Ref <> 0
in first condition. Therefore my code will not reach the declaration of @XYZ
(line 2).
I think it must raise an error in the second IF
because of @XZY
was not declared.
But I'm surprised that there is no error raised.
IF @Ref = 0
BEGIN
DECLARE @XYZ int
SELECT @XYZ = RISKGROUP
FROM POLCONT WITH (NOLOCK, NOWAIT)
WHERE CONT = 555
END
IF @RISKGROUP <> @XYZ
BEGIN
-- do something ...
END
For example.
In python it raises this error:
Error: local variable 'XYZ' referenced before assignment
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要先用类型声明变量,然后才能使用它
编辑
自从我发布了答案以来,您改变了您的问题,现在您的问题是您在错误的范围内声明了变量。
编辑2
至于你的问题为什么它没有给出任何错误,这确实很奇怪
看到这个DBFiddle
我确实希望出现错误,但不知何故它不会出现
这在 文档 按设计正常,尽管在我看来这是一个缺陷。
另请参阅此问题关于同一主题
编辑3
因此,在声明变量的TSQL中,这似乎并不重要,但作为一名程序员,我发现这看起来很奇怪,所以我更喜欢将变量放在为了我正确的范围。
You need to declare your variable with a type before you can use it
EDIT
You altered your question since I have posted my answer, now your problem is you declare the variable in the wrong scope.
EDIT 2
As to your question why it does not give any error, that is strange indeed
See this DBFiddle
I would indeed expect an error, but it somehow does not
This is explained in the documents as normal per design, though in my mind it is a flaw.
Also see this Question about the same subject
EDIT 3
So it seems that is does not matter much in TSQL where you declare your variables, but as a programmer I find this looking weird, so I prefer to put my variables in what is for me the correct scope.