Determining if a query returns 'no rows' in vb.net

后端 未结 2 1908
你的背包
你的背包 2021-01-25 11:41

I am using MS SQL Server as my database and VB.NET as my back-end.

I want to determine if my query in sql command text returns no rows. I tried to have a query that retu

相关标签:
2条回答
  • 2021-01-25 12:19
            Dim RowsReturned As Integer
            Cmd.CommandText = "SELECT * FROM tblExample WHERE PKeyNo =999"
            cmd.CommandType = CommandType.Text
    
    
            RowsReturned = cmd.ExecuteScalar()
    
            If RowsReturned = 0 Then
                    'No rows
            Else 
               'Has Rows
    
    0 讨论(0)
  • 2021-01-25 12:21

    @podiluska is right. You will have to execute the command. As I can see you have assigned value for the CommandText property of Command object that’s the query you want to execute. In order to execute the command, you must have an open active connection followed by call to Execute method on command object. Following pseudo code might help:

    Public Sub Temp(ByVal connectionString As String)
        Dim queryString As String = _
           " select * from example where id = 999;" 
        Using connection As New SqlConnection(connectionString)
            Dim command As New SqlCommand(queryString, connection)
            connection.Open()
            Dim reader As SqlDataReader = command.ExecuteReader()
            Try 
                If reader.Read() Then
                   'If condition
                Else
                   'condition with  no results
                End If
            Finally 
                reader.Close()
            End Try 
         End Using 
    End Sub
    
    0 讨论(0)
提交回复
热议问题