2

we got this sql query:

Select EmployeeDesignation from Employee where EmployeeName = Paramater1 

(Parameter1 is value is passed to this)

We are using this statement: lEmployeeDesignation = _SQLCommand.ExecuteScalar()

3 scenario's:

  1. Returns the employee Designation (record exists in table)
  2. No value is set in database for Parameter1 - so should return NULL (record exists but has no value)
  3. No employee record exists so returns nothing (record doesn't exists)

I'm struggling with 2 and 3 scenario - incase of Scenario 3 we want the application to fail, but struggling how to trap this error. regards

2 Answers 2

1
lEmployeeDesignation = _SQLCommand.ExecuteScalar()
if lEmployeeDesignation IsNot Nothing AndAlso lEmployeeDesignation <> DBNull.Value then
    ' you have found your data....' 
Else
    if lEmployeeDesignation = DBNull.Value then
       ' you have a record for parameter1 but EmployeeDesignation field is null'
    End If
End If

Notice the use of AndAlso to shortcircuit the evaluation process. If the first condition is false then the second one is not evaluated

Sign up to request clarification or add additional context in comments.

2 Comments

In the case where lEmployeeDesignation Is Nothing, then wouldn't this throw an exception when evaluating "if lEmployeeDesignation = DBNull.Value"? Wouldn't you also want to preface that evaluation with "if lEmployeeDesignation IsNot Nothing AndAlso..."?
I like when someone, 4 years after the answer, downvote it and doesn't leave any comment to explain what he/she has fount to be wrong. I was very new to the site at that time but still today I can't see where this answer is wrong.
0

You could eliminate the Null entirely by...

Select IsNull(Max(EmployeeDesignation),0) from Employee where EmployeeName = Paramater1

It's not a terribly good thing to do, but it works and as long as you're not doing too many of them it'll be fine.

You could also put in a Count(EmployeeDesignation)=0 to check scenario 3 though of course this couldn't be done on the same query or you would have to use a reader

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.