我使用以下函数来计算给定项目代码(vb.net、sqlserver、sql)的sum qty值。我没有得到任何错误,但是函数返回的值总是 -1
. 数据见下表(附屏幕截图)。我想,我的代码中缺少了一些东西,但却找不出来。如有任何建议,我们将不胜感激。
Public Function findPurchaseQty(ByVal itCode As String, ByVal fromDate As DateTime, toDate As DateTime) As Double
Dim sql = "SELECT sum(purchase_qty) FROM TB_STOCK WHERE it_code = @it_code AND added_date >= @added_date_start AND added_date < @added_date_end"
Dim command As New SqlCommand(sql, conn)
With command.Parameters
.Add("@it_code", SqlDbType.VarChar, 50).Value = itCode
.Add("@added_date_start", SqlDbType.DateTime).Value = fromDate
.Add("@added_date_end", SqlDbType.DateTime).Value = toDate
End With
Dim purchaseTotal As Double = command.ExecuteNonQuery()
Return purchaseTotal
End Function
我执行如下测试函数,但稍后计划从日期时间选择器获取值,
Dim fromDate As DateTime = "2020-07-20 00:00:00"
Dim toDate As DateTime = "2020-07-22 23:59:59"
Dim itCode As String = "0001"
MsgBox(findPurchaseQty(itCode, fromDate, toDate))
1条答案
按热度按时间yptwkmov1#
就像名字上说的那样
ExecuteNonQuery
不是一个正确的方法SELECT
因为它返回受影响的行数,而不是SELECT
-查询。你要找的是
ExecuteScalar
作为ExecuteScalar
返回一个Object
你必须把结果交给Double
.正如评论中提到的,检查
ExecuteScalar()
返回一个数字而不是DBNull.Value
,以防止DirectCast
避免失败。