我收到一条错误消息:
“运算符'+'未定义为'整数'类型,并键入'DBNull'。”
突出显示:
TotalBoxes + = TotalBoxescmd.ExecuteScalar
我以为我正在使用我的sql命令设置方式将DBNull值转换为零。这就是我所拥有的,我没有正确地将dbnull值格式化为零?
For Each item As Object In chkLstShipments.CheckedItems
Dim checkedItem As Integer
checkedItem = Val(item)
Dim TotalBoxescmd As New SqlCommand("Select sum(isnull(LineBoxes, 0)) FROM ShipmentLineTable Where ShipmentNumber = @ShipmentNumber", con)
TotalBoxescmd.Parameters.AddWithValue("@ShipmentNumber", checkedItem)
If con.State = ConnectionState.Closed Then con.Open()
TotalBoxes += TotalBoxescmd.ExecuteScalar
con.Close()
Next
答案 0 :(得分:2)
您应该检查TotalBoxes
声明,以确保它已正确初始化
(例如0
或前一生。)
顺便说一句,您需要将ISNULL
函数移到SUM
之外,以防没有给定ShipmentNumber
的行返回。您ISNULL
内部不需要SUM
因为SUM
函数正确处理NULL
值。
ISNULL(SUM(LineBoxes), 0)
如果ShipmentNumber
必须有效,请在调试模式下检查参数的实际值,值恢复机制可能是错误的。
这里有使用和不使用ISNULL处理SUM的示例,
有或没有线。
以下数据:
SELECT DISTINCT [myColumn] FROM [myTable]
myColumn
---------------
NULL
3
5
SELECT SUM([myColumn]) as [SumWithoutIsNull]
FROM [myTable]
WHERE 0=1
SumWithoutIsNull
---------------------------------------
NULL
SELECT SUM([myColumn]) as [SumWithoutIsNull]
FROM [myTable]
SumWithoutIsNull
---------------------------------------
8
Warning: Null value is eliminated by an aggregate or other SET operation.
SELECT ISNULL(SUM([myColumn]), 0) as [SumWithIsNull]
FROM [myTable]
WHERE 0=1
SumWithIsNull
---------------------------------------
0
SELECT ISNULL(SUM([myColumn]), 0) as [SumWithIsNull]
FROM [myTable]
SumWithIsNull
---------------------------------------
8
Warning: Null value is eliminated by an aggregate or other SET operation.
答案 1 :(得分:1)
用于代码sql
ISNULL(SUM(LineBoxes), 0)
或者
在您的代码VB
中 TotalBoxes += TotalBoxescmd.ExecuteScalar
if TotalBoxes is nothing then
TotalBoxes = 0
end if