<!-- Function 1-->
Function GetStudentResultTotal(ByVal schid As String, ByVal level As String, ByVal session As String, ByVal term As String, ByVal klass As String, ByVal regno As String) As Double
If SCH_ID <> "" Then
schid = SCH_ID
End If
Dim total As Double = 0
Dim subjectCount As Integer = 0
Dim fields As New ArrayList
fields.Add("SUM(" & StudentData.Total & ") AS GrandTotal")
Dim filterValues As New Hashtable
filterValues.Add(StudentData.SchoolID, schid)
filterValues.Add(StudentData.Level, level)
filterValues.Add(StudentData.Session, session)
filterValues.Add(StudentData.Term, term)
filterValues.Add(StudentData.Klass, klass)
filterValues.Add(StudentData.RegNo, regno)
Dim filterArgs As String = "WHERE " & StudentData.SchoolID & "=@" & StudentData.SchoolID & " AND " & StudentData.Level & "=@" & StudentData.Level & " AND " & StudentData.Session & "=@" & StudentData.Session & " AND " & StudentData.Term & "=@" & StudentData.Term & " AND " & StudentData.Klass & "=@" & StudentData.Klass & " AND " & StudentData.RegNo & "=@" & StudentData.RegNo
Dim data As DataSet = _Data.GetData(StudentData.tblStudentResult, fields, filterValues, filterArgs)
'If data.Tables(0).Rows.Count > 0 Then
' For Each dr As DataRow In data.Tables(0).Rows
' total += CDbl(NormalizeRecord(dr(StudentData.Total)))
' subjectCount += 1
' Next
'End If
Dim dr As DataRow = data.Tables(0).Rows(0)
total = CDbl(dr("GrandTotal"))
Return total
End Function
<!-- Function 2-->
Function GetData(ByVal tbl As String, ByVal values As ArrayList, ByVal filters As Hashtable, ByVal filterArgs As String) As DataSet
Dim _ds As New DataSet
Dim sql As String = "SELECT "
Dim fields As String = ""
Using conn As New MySqlConnection(connString)
conn.Open()
If values IsNot Nothing Then
For i = 0 To values.Count - 1
If fields = "" Then
fields = values.Item(i).ToString
Else
fields &= "," & values.Item(i).ToString
End If
Next
sql &= fields & " "
End If
sql &= "FROM " & tbl
If filterArgs <> "" Then
sql &= " " & filterArgs
End If
Dim cmd As New MySqlCommand(sql, conn)
If filters IsNot Nothing Then
For i = 0 To filters.Count - 1
cmd.Parameters.AddWithValue("@" & filters.Keys(i), filters.Values(i))
Next
End If
Dim da As New MySqlDataAdapter(cmd)
da.Fill(_ds)
conn.Close()
End Using
Return _ds
End Function
<!-- Function 3-->
Function NormalizeRecord(ByVal value As String) As String
If value = "-" Then
value = "0"
End If
Return value
End Function
我的代码中描述的函数1应该对列总数求和并返回结果,但如果返回空值,尤其是第一次插入记录时,它总是抛出错误(从dbnull类型转换为double类型无效)。我如何控制空值?
1条答案
按热度按时间eeq64g8w1#
好吧,有两种方法可以解决。
首先,您可能没有行,或者返回的ONLY行具有空值。
如果你执行了一个“sum()",那么如果任何一行不为空,那么你将得到一个值。
但是,如果没有行,或者行中的列为空,那么您将看到/get/find为空。
因此,一个简单的解决方法是使用isnull。
所以,你的代码可以这样写:
以上可能是您最好的选择,因为即使查询由于过滤而不返回任何行,您仍然会得到一个0。
编辑:我看到您将其标记为MySQL,而不是SQL Server -我的错误,所以我建议使用以下解决方案。
然而,您经常会在数据表中遇到空值(顺便说一句,为什么要使用数据集来代替数据表?这里不需要数据集,因为没有表集合)。
那么,接下来,因为你经常做这个?
在你的“全系统”实用程序包中放入:
现在你可以这样说:
您可以修改SQL查询,并让它为那些空行返回0值。