在visual basic和SQL Server中将null值替换为0

时间:2017-05-31 14:16:26

标签: sql-server vb.net aggregate-functions isnull dbnull

我收到一条错误消息:

  

“运算符'+'未定义为'整数'类型,并键入'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            

2 个答案:

答案 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     

没有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.

答案 1 :(得分:1)

用于代码sql

ISNULL(SUM(LineBoxes), 0)

或者

在您的代码VB

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