1

I have entered a user's name that exists in the DB. The name has only first and last name. so the middle name is empty and it is stored in the DB as null. To get the employee id of the user, i have used the following query. but the value of obj after executing the query is null. The first and last names are stored in an array. I have checked their values. Their values are ok.

Can you please tell me why the object is not fetching nay value.

SqlCommand cmm1= new SqlCommand ();
cmm1.CommandText = ("Select empID from empPersonalInfo where empFirstName= '" + arr[0].ToString() + "' and empMiddleName= '" + System.DBNull.Value + "' and empLastName= '" + arr[2].ToString() + "' ");            
cmm1.Connection = conn;
obj = cmm1.ExecuteScalar();

5 Answers 5

3

You can't compare NULL using equals '=', use 'IS NULL' instead:

cmm1.CommandText = ("Select empID from empPersonalInfo where empFirstName= '" + 
              arr[0].ToString() + "' and empMiddleName IS NULL and empLastName= '" + 
              arr[2].ToString() + "' ");    

BTW, that query really doesn't make a lot of sense. Perhaps :

empMiddleName IS NULL OR empMiddleName =  @somevalue

Plus, please note: you are possibly open to SQL Injection attacks. Use parameters rather than concatenating user input values.

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

Comments

2

For comparing a field against null use empMiddleName IS NULL

You should use Parameterized queries to prevent SQL injection.

Comments

1

empMiddleName= '" + System.DBNull.Value + "' is incorrect. There is no = operator for NULL value.

Change it to empMiddleName is null .

Comments

0

Use SQLParameter object for passing parameters to the query as below:

SqlCommand command = 
        new SqlCommand("SELECT * FROM Users WHERE Username = @Username", conn);

    command.Parameters.Add(new SqlParameter("@Username", "Justin Niessner"));
    obj = command.ExecuteScalar();

Comments

0
You need to check that middle name should be equal null or middle name should be equal to value you have passed in query.

I hope blow query query can full fill your requirement.

cmm1.CommandText = ("Select empID from empPersonalInfo where empFirstName= '" + 
                  arr[0].ToString() + "' and ((empMiddleName IS NULL) or(empMiddleName='"+arr[1].ToString()+"')) and empLastName= '" + 
                  arr[2].ToString() + "' ");   

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.