I would recommend not using IsNull()
in this scenario, but to answer the question about the syntax error first.
The reason is the <%= %>
syntax which is shorthand for
<% Response.Write %>
in Classic ASP.
So what you are actually doing if written without the shorthand approach is;
<% Response.Write If Not IsNull(rs("ContractValue")) Then FormatNumber(rs("ContractValue"),0) End If %>
which is incorrect syntax and will trigger a Syntax Error
.
To fix the code remove the =
from the <% %>
tags, like so;
<% If Not IsNull(rs("ContractValue")) Then Response.Write FormatNumber(rs("ContractValue"),0) End If %>
What about using IsNull
?
While this can work it can often give weird results because a DBNull (depending on the database being used) can be different and is often different to the VBScript vbNull
variant.
Because of this and the fact VBScript isn't strongly typed I find it useful to use a simple quick cast to string to avoid Nulls then check for valid data.
Example numeric check
Dim contractValue
contractValue = rs("ContractValue") & ""
If Len(contractValue) > 0 And IsNumeric(contractValue) Then contractValue = Clng(contractValue) Else contractValue = 0
You can take this further by writing a reusable piece of code that IIf()
function explained in this post.
Something like this;
Dim contractValue
contractValue = rs("ContractValue") & ""
contractValue = IIf(Len(contractValue) > 0 And IsNumeric(contractValue), contractValue, 0)
@Paul made a good point 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.