sqlCommand.ExecuteScalar problem on return value

  • Thread starter Thread starter RA
  • Start date Start date
R

RA

Hi

"Select UserId from users where userid = 2"

How come it return Undefined value if the select doesn't return any result?
How can I know if the select succeded or not?

Thanks,
Ronen
 
There's nothing to return, so it comes back null. The short answer is that
you can check to see if it's null or not. You might also want to consider
using an Output parameter and restructure your query. Bill Vaugh has a
great article on MSDN.

Depeding on what the ultimate logic of your app is, you might also want to
use a Count(*) but that will only work if you only need to know that a value
exists or not, not if you need it.

I think an Output param may do it for you.

HTH,

Bill
 
Ronen,

I used the following code to talk to SQL Server's Northwind database.

Dim cmd As SqlCommand = cn.CreateCommand
cmd.CommandText = "select employeeid from employees where employeeid=10"

Dim i As Integer = cmd.ExecuteScalar()
MessageBox.Show(i)

EmplyeeID = 10 doesn't exist in the table so I got in the MessageBox the value of 0.

So in your case, not sure why you are getting this. What backend database are you using?

If you would like to know if any results are coming back or not then you shouldn't use the ExecuteScalar method. You should use the DataReader and then call the Read
property.

I hope this helps!


Thanks,
Hussein Abuthuraya
Microsoft Developer Support

This posting is provided "AS IS" with no warranties, and confers no rights.

Are you secure? For information about the Microsoft Strategic Technology Protection Program and to order your FREE Security Tool Kit, please visit
http://www.microsoft.com/security.
 
No its not comming as null. The return is comming back as Undefined value -
I would expect to get dbnull value if nothing is comming back.

Ronen
 
Back
Top