0

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 returns no rows, and then give its value to a text box which became 0. (integer)

The problem now, is that when I test it in an If condition, it doesn't work. The code is like this:

If (Query that returns no rows) = 0 Then
'condition
Else
'condition
End If

I tried a blank string, but it still does not work. Please help! If possible, please give the simples solution to the problem. Thank you in advance!

6
  • And how are you calling this query? Commented Sep 30, 2013 at 7:14
  • you should be able to use !<enumerable>.Any(), but... hard to say more with the given code ! Commented Sep 30, 2013 at 7:16
  • Like this cmd.CommandText = "select * from example where id = 999" Commented Sep 30, 2013 at 7:19
  • @LorenzoSalamante and then what...? Commented Sep 30, 2013 at 7:42
  • 1
    You have to execute the query. Otherwise nothing is happening. This will be much easier to fix if you paste ALL of the relevant code. Commented Sep 30, 2013 at 7:55

2 Answers 2

1

@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
Sign up to request clarification or add additional context in comments.

1 Comment

if reader.read is true, how would you be able to tell how many records were found?
0
        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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.