0

When I run the following SQL statement in SQL Server Management Studio it returns a count of 2

SELECT COUNT(*) 
FROM Daisy_Copy2 
WHERE ChargeCode = '1';

But for some reason when I run the following VB.net code the result variable returns a 0 and doesn't identify that duplicate codes exist.

Dim result As Integer
Using cmdb = New SqlCommand("SELECT COUNT(*) FROM Daisy_Copy2 WHERE ChargeCode = '1'", conn)

Int(result = cmdb.ExecuteScalar())

If result > 1 Then
   MessageBox.Show("Duplicate Codes Exist!", "Billing", _
   MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
   MsgBox(result)
End If
End Using

Can anyone help me understand why?

Any help greatly appreciated.

3
  • Thank you for your replies, I have changed the code from ExecuteNonQuery to Int(result = cmdb.ExecuteScalar()), but it still returns 0 ? I am new to VB, so I may have the syntax wrong? Thanks Commented May 14, 2014 at 19:46
  • updated with vb.net syntax - try my updated answer Commented May 14, 2014 at 19:56
  • Thanks Morten, it works with the updated Syntax Commented May 14, 2014 at 20:05

3 Answers 3

2

Instead of ExecuteNonQuery you should use ExecuteScalar

Dim result As Integer = CInt(cmd.ExecuteScalar())
Sign up to request clarification or add additional context in comments.

Comments

2

ExecuteNonQuery is normally used for updates or inserts that don't leave a result, so it returns an integer telling you how many rows were affected, not the result itself.

What you most likely are meaning to use is ExecuteScalar which returns the first column of the first row in the result set returned by the query, in this case the integer containing your count.

Comments

0

this is just a way you can use:

Dim Sqlda = New SqlDataAdapter("SELECT COUNT(*) AS tCount FROM Daisy_Copy2 WHERE ChargeCode=1", conn)
Dim sqlds = New DataSet



Sqlda.Fill(sqlds, "Daisy_Copy2")

Dim tblRow As DataRow
For Each tblRow In sqlds.Tables("Daisy_Copy2").Rows
    MsgBox(tblRow("tCount").ToString())
Next

use below link to read more about it

System.Data.SqlClient Namespace

Good luck

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.