Dieter
Dieter

Reputation: 441

select NULL value from sql server db

i'm having a problem with a select statement.

It looks like:

myda = new SqlDataAdapter("Select * FROM tblAgenda WHERE tAgUsrId ='" + Session["usrId"] + "' AND tAgTBD = '" + Session["username"] + "' OR tAgTBD = '" + DBNull.Value + "' ", myconn);

But I have no idea how to make that DBNull.Value work. I also tried with just using "" instead, but it also doesn't work.

Any ideas on how to rewrite this statement please? Thank you.

Upvotes: 0

Views: 4977

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239764

Assuming that your session values have already been sanitised, then you can do the following:

myda = new SqlDataAdapter("Select * FROM tblAgenda WHERE tAgUsrId ='" +
    Session["usrId"] + "' AND tAgTBD = '" +
    Session["username"] + "' OR tAgTBD is null", myconn);

The above assumes that you want all rows where tAgTBD are null. If you want to keep the restriction the to the user ID, you'll want to add brackets around the two ORed conditions:

myda = new SqlDataAdapter("Select * FROM tblAgenda WHERE tAgUsrId ='" +
    Session["usrId"] + "' AND (tAgTBD = '" +
    Session["username"] + "' OR tAgTBD is null)", myconn);

If the session values haven't been sanitised, then you need to read up on SQL injection, and look at using an SqlCommand with parameters instead of constructing a string; although you may prefer to go this route anyway - it's a better habit to acquire, long term, and then you don't need to consider whether the values have been sanitised.

Upvotes: 1

Related Questions