循环访问SQLdatareader并比较行值

时间:2015-08-11 15:24:04

标签: sql vb.net sqldatareader

我有一个调用存储过程的函数。我需要将结果与输入参数进行比较。我不断收到警告,该函数不会在所有代码路径上返回,但我无法弄清楚在哪里。

所以,2个问题: 1.我是否正确地遍历SqlDataReader或者我应该用我的读者结果填充数据表吗? 2.我在哪里错过了返回值?

功能代码:

Function FZCheck(FZ As String) As Boolean

    Dim constr As String = My.Settings.devTOD.ToString
    Dim con As New SqlConnection(constr)

    Dim cmd As New SqlCommand("spSelectFloodZones", con)
    cmd.CommandType = CommandType.StoredProcedure

    If con.State = ConnectionState.Closed Then
        con.Open()
    End If

    Dim rdr As SqlDataReader
    rdr = cmd.ExecuteReader

    If rdr.HasRows Then
        Do While rdr.Read
            If String.Equals(rdr(0).ToString, FZ) = True Then
                Return True
            Else
                Return False
            End If
        Loop
    Else
        Return False
    End If

    If con.State = ConnectionState.Open Then
        con.Close()
    End If

    rdr.Close()

End Function

存储过程代码:(非常简单)

ALTER PROCEDURE [dbo].[spSelectFloodZones]
AS
    SET NOCOUNT ON
    SET ROWCOUNT 0

-- ====================
-- Select flood zones
-- ====================

SELECT DISTINCT FloodZone
FROM TOD.dbo.FloodZones

语言是VB.NET,使用SQL Server 2012。

1 个答案:

答案 0 :(得分:1)

在这里你进行一些小的重构。

Function FZCheck(FZ As String) As Boolean
        Dim constr As String = My.Settings.devTOD.ToString
        Dim con As New SqlConnection(constr)
        Dim result As Boolean = False

        Dim cmd As New SqlCommand("spSelectFloodZones", con)
        cmd.CommandType = CommandType.StoredProcedure

        If con.State = ConnectionState.Closed Then
            con.Open()
        End If

        Dim rdr As SqlDataReader
        rdr = cmd.ExecuteReader

        If rdr.HasRows Then
            Do While rdr.Read
                If String.Equals(rdr(0).ToString, FZ) = True Then
                    result = True
                End If
            Loop
        End If

        If con.State = ConnectionState.Open Then
            con.Close()
        End If
        rdr.Close()
        Return result
    End Function