在 Visual Basic 和 SQL 服务器中用 0 替换空值

Replacing null values with 0 in visual basic and SQL Server

我收到一条错误消息:

"Operator '+' is not defined for type 'Integer' and type '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            

您应该检查 TotalBoxes 声明以确保它已正确初始化
(例如在 0 或前世)。

顺便说一句,您需要将 ISNULL 函数移到 SUM 之外,以防给定的 return 行没有=20=]。 SUM 中不需要 ISNULL,因为 SUM 函数可以正确处理 NULL 值。

ISNULL(SUM(LineBoxes), 0)

此外,如果ShipmentNumber 必须有效,请在调试模式下检查参数的真实值,值恢复机制可能是错误的。

例子

这里的例子说明了在有和没有 ISNULL 的情况下如何处理 SUM,
有线或无线。

对于以下数据:

SELECT DISTINCT [myColumn] FROM [myTable]

myColumn
---------------
NULL
3         
5     

没有 ISNULL

没有线条

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.

与 IsNull

没有线条

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.

用于代码 sql

ISNULL(SUM(LineBoxes), 0)

在你的代码中VB

 TotalBoxes += TotalBoxescmd.ExecuteScalar
 if TotalBoxes is nothing then
 TotalBoxes = 0
 end if