executenonquery始终返回-1,即使sql语句是正确的

zbsbpyhn  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(353)

我使用以下函数来计算给定项目代码(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))

yptwkmov

yptwkmov1#

就像名字上说的那样 ExecuteNonQuery 不是一个正确的方法 SELECT 因为它返回受影响的行数,而不是 SELECT -查询。
你要找的是 ExecuteScalar 作为 ExecuteScalar 返回一个 Object 你必须把结果交给 Double .

Dim purchaseTotal As Double = DirectCast(command.ExecuteScalar(), Double)

正如评论中提到的,检查 ExecuteScalar() 返回一个数字而不是 DBNull.Value ,以防止 DirectCast 避免失败。

Dim result As Object = command.ExecuteScalar()
Dim purchaseTotal As Double
If Not DBNull.Value.Equals(result) Then
    purchaseTotal = DirectCast(result, Double)
End If

相关问题