注册 登录
编程论坛 VB.NET论坛

如何处理SQL查询返回空值的问题,求助!

mkb21 发布于 2008-05-25 21:31, 2758 次点击
WinFrm过程代码:
    public myItem as String    '用于返回值的公共变量
    Public Sub DatSearch(ByVal TabName As String, ByVal Field As String, ByVal Guide As String)
        CmdText = "Select " & Field & " From " & TabName & " Where " & Guide
        If Conn.State = 1 Then Conn.Close() ‘若Conn连接,则关闭它
        Dim Cmd As SqlClient.SqlCommand = New SqlClient.SqlCommand(CmdText, Conn)’新建数据连接
        SQLAdp.SelectCommand = New SqlClient.SqlCommand(CmdText, Conn)‘新建数据查询命令
        Try
            Conn.Open()                                                           '连接数据库
            SQLAdp.Fill(DataSet, "SearchTab")                        '填充数据集缓存
            Dim myResp As Object = Cmd.ExecuteScalar         '判断是否存在记录

       if myResp Is System.DBNull Then
                     myItem =Nothing                                   '如果myResp为空
            Else
                    myItem =DataSet.Tables("SearchTab").Rows(0).Item(0)
            End if

            DataSet.Tables("SearchTab").Clear()
            DataSet.Tables.Remove("SearchTab")
            Conn.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
            Exit Try
        End Try
    End Sub

上述代码在执行时,当查询返回空记录时,会出错:“在0处没有任何行!”,问题在哪里?
怎样才能处理出现空值或空记录的情况,谢谢高手指点!
2 回复
#2
tntzwc2008-05-26 00:02
DBNull.Value
用这个试一下
#3
iceqier2008-05-27 17:28
if myResp Is System.DBNull Then
myItem =Nothing                                   '如果myResp为空
Else
myItem =DataSet.Tables("SearchTab").Rows(0).Item(0)
End if

 if myResp Is System.DBNull Then 改成 if DataSet.Tables("SearchTab").Rows.Count<=0
1