gpt4 book ai didi

SQL -VB - 即使 if 为真,它是否评估 else ?

转载 作者:行者123 更新时间:2023-12-04 16:11:15 25 4
gpt4 key购买 nike

我试图防止 #error 显示在我正在创建的报告中

当我除以 2 个数字并且其中一个为零时会发生这种情况

所以我尝试使用 if/switch 语句在执行除法之前检查两个数字中的任何一个是否为 0:

    =IIf(Fields!Field1.Value = 0 
or Fields!Field2.Value = 0
or Not(IsNumeric(Fields!Field1.Value))
or Not(IsNumeric(Fields!Field2.Value)),
0,
(Fields!Field1.Value/Fields!Field2.Value)*100
)


=Switch(
Fields!Field1.Value = 0 or Fields!Fields.Value = 0, 0,
IsNumeric(Fields!Field1.Value) or IsNumeric(Fields!Fields.Value), (Fields!Field1.Value/Fields!Fields.Value)*100
)

这两个仍然抛出错误。即使if语句为真,似乎仍然评估else条件

如果我将代码更改为只为 if 和 else 打印 X 或 Y,则它可以工作 - 所以 if 语句中没有错误

这对我来说很荒谬

请告诉我我做错了什么?我不敢相信当 if 为真时,语言会评估 else

编辑

所以似乎对else条件进行了评估。那么你如何解决潜在的除以零误差的问题呢?

这是来自以下内容的答案:
http://www.sqlservercentral.com/Forums/Topic442497-150-1.aspx#bm1115960

另一种选择(特别是如果您有一个包含许多可能导致除以零情况的表达式的报告)是使用自定义代码函数。

在报告属性的代码选项卡/窗口中,输入如下内容:
Public Function DivideBy(ByVal Exp1, ByVal Exp2)
If Exp2 = 0 Then
DivideBy = 0
Else : DivideBy = Exp1 / Exp2
End If
End Function

然后插入表达式
=code.DivideBy(Field!ToBeDivided.Value,Field!DividingBy.Value)
进入任何有可能被零除问题的单元格。

最佳答案

是的,IIf 函数的 true 和 false 部分都会被评估:

http://en.wikipedia.org/wiki/IIf#Side_Effects

Side Effects
Another issue with IIf arises because it is a library function: unlike the C-derived conditional operator, both truepart and the falsepart will be evaluated regardless of which one is actually returned. Consider the following example:

value = 10 
result = IIf(value = 10, TrueFunction, FalseFunction)

Although TrueFunction is the function intended to be called, IIf will cause both TrueFunction and FalseFunction to be executed.

Also consider this one:

a = 10 
b = 0
result = IIf(b <> 0, a / b, 0)

While the programmer intends to avoid raising an error by performing a division by zero, whenever b is zero the error will actually happen. This is because the code in the snippet is to be read as

a = 10 b = 0
_temp1 = a / b ' Error if b = 0
_temp2 = 0
_temp3 = b <> 0 result = IIf(_temp3, _temp1 , _temp2)

This issue makes the IIf() call less useful than the conditional operator. To solve this issue, Microsoft developers had considered converting IIf to an intrinsic function; had this happened, the compiler would have been able to perform type inference and short-circuiting by replacing the function call with inline code.

关于SQL -VB - 即使 if 为真,它是否评估 else ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7040408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com