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();
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.
For comparing a field against null
use empMiddleName IS NULL
You should use Parameterized queries to prevent SQL injection .
empMiddleName= '" + System.DBNull.Value + "' is incorrect. There is no = operator for NULL value.
Change it to empMiddleName is null .
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();
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() + "' ");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.