IF 语句未按预期引发错误

发布于 2025-01-19 11:49:42 字数 502 浏览 5 评论 0原文

假设 @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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

溇涏 2025-01-26 11:49:42

您需要先用类型声明变量,然后才能使用它

declare @xyz int -- assuming the datatype of column riskgroup is also int

select @xyz = riskgroup
from   polcont
where  polcont = 555

编辑

自从我发布了答案以来,您改变了您的问题,现在您的问题是您在错误的范围内声明了变量。

DECLARE @XYZ int

if @Ref = 0 
begin 
   SELECT @XYZ = RISKGROUP
   FROM   POLCONT --WITH (NOLOCK, NOWAIT) don't do nolock everywhere !
   WHERE  CONT = 555
end

if @RISKGROUP <> @XYZ  
begin
   -- do something ...
end

编辑2

至于你的问题为什么它没有给出任何错误,这确实很奇怪

看到这个DBFiddle
我确实希望出现错误,但不知何故它不会出现

这在 文档 按设计正常,尽管在我看来这是一个缺陷。
另请参阅此问题关于同一主题

编辑3

因此,在声明变量的TSQL中,这似乎并不重要,但作为一名程序员,我发现这看起来很奇怪,所以我更喜欢将变量放在为了我正确的范围。

You need to declare your variable with a type before you can use it

declare @xyz int -- assuming the datatype of column riskgroup is also int

select @xyz = riskgroup
from   polcont
where  polcont = 555

EDIT

You altered your question since I have posted my answer, now your problem is you declare the variable in the wrong scope.

DECLARE @XYZ int

if @Ref = 0 
begin 
   SELECT @XYZ = RISKGROUP
   FROM   POLCONT --WITH (NOLOCK, NOWAIT) don't do nolock everywhere !
   WHERE  CONT = 555
end

if @RISKGROUP <> @XYZ  
begin
   -- do something ...
end

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文