lak*_*han 2 sql vb.net sql-server executenonquery
I'm using the following function to calculate sum qty value of given item code(VB.NET, SQL Server, SQL). I do not get any errors but the returned value by the function is always -1. The data is available in the table(Screenshot attached). I think, something is missing in my code but cant figure it out. Any advice will be highly appreciated.
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
Run Code Online (Sandbox Code Playgroud)
I execute the function for testing as follows but later plan to take values from date time picker,
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))
Run Code Online (Sandbox Code Playgroud)
顾名思义,这ExecuteNonQuery不是 a 的正确方法,SELECT因为它返回受影响的行数,而不是SELECT-Query的结果。
你要找的是 ExecuteScalar
作为ExecuteScalar返回 aObject您必须将结果转换为 a Double。
Dim purchaseTotal As Double = DirectCast(command.ExecuteScalar(), Double)
Run Code Online (Sandbox Code Playgroud)
正如评论中提到的,检查是否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
Run Code Online (Sandbox Code Playgroud)