ASP 经典中的 If Not IsNull

If Not IsNull in ASP Classic

我是 asp 的新手,我有一个语法错误,如果可以的话,我希望得到帮助。

我有一个 ASP 页面显示 table 从 sql 中提取数据。大多数数据尚未填充,因此 returns 为 NULL。有问题的数据类型是数字。我需要 FormatNumber rs 当它不为 null 时不填充它。

这就是我的

<%=If Not IsNull(rs("ContractValue")) Then FormatNumber(rs("ContractValue"),0) end if%>

但如前所述,我遇到语法错误。

我做错了什么?

我建议在这种情况下不要使用 IsNull(),而是先回答有关语法错误的问题。

原因是 <%= %> 语法,shorthand for

<% Response.Write %>

经典 ASP.

因此,如果没有使用 shorthand 方法编写,您实际做的是;

<% Response.Write If Not IsNull(rs("ContractValue")) Then FormatNumber(rs("ContractValue"),0) End If %>

语法不正确,会触发 Syntax Error.

要修复代码,请从 <% %> 标签中删除 =,像这样;

<% If Not IsNull(rs("ContractValue")) Then Response.Write FormatNumber(rs("ContractValue"),0) End If %>

使用 IsNull 怎么样?

虽然这可行,但通常会产生奇怪的结果,因为 DBNull (取决于所使用的数据库) 可能不同,而且通常与 VBScript vbNull变体。

由于这个原因以及 VBScript 不是强类型的事实,我发现使用简单的快速转换为字符串以避免空值然后检查有效数据很有用。

数字检查示例

Dim contractValue
contractValue = rs("ContractValue") & ""
If Len(contractValue) > 0 And IsNumeric(contractValue) Then contractValue = Clng(contractValue) Else contractValue = 0

您可以通过编写一段可重复使用的代码来更进一步,IIf() 函数在 post.

中对此进行了解释
  • How to do a single line If statement in VBScript for Classic-ASP? ( by @TasosK在评论中)

像这样;

Dim contractValue
contractValue = rs("ContractValue") & ""
contractValue = IIf(Len(contractValue) > 0 And IsNumeric(contractValue), contractValue, 0)

@Paul about evaluation of parameters, in the original code would potentially break

contractValue = IIf(Len(contractValue) > 0 And IsNumeric(contractValue), Clng(contractValue), 0)

because Clng(contractValue) would be evaluated regardless of whether the outcome was True or False. So any formatting would need to be afterwards or a more complex version of the IIf() function be built.

If Not IsNull(rs("ContractValue")) Then 
    <%=FormatNumber(rs("ContractValue"),0)%>
end if

不要着急使用经典 ASP。

我确定您想在某些 HTML 代码之间插入内容,这让您将所有代码组合在一起。如果是这样,我建议您将 VBscript 代码与 HTML 分开,如下所示;

<%
Dim valueToOutput

If Not IsNull(rs("ContractValue")) Then 
        valueToOutput=FormatNumber(rs("ContractValue"),0)
    end if
%>

<!-- HTML Code continues below with an inserted VBscript variable -->

There are a total of <%=valueToOutput%> oranges available!