Suppose I’m querying a table, and null might be one of the values to look for. A query that’s set up like this
command.CommandText = "select * from People where Saluation = @salutation";
if(salutation != null) command.Parameters.AddWithValue("@salutation", salutation);
else command.Parameters.AddWithValue("@salutation", DBNull.Value);
won’t return any results when salutation is null. So I’m inclined to do this instead, but it feels ugly to me:
string whereClause;
if(!string.IsNullOrEmpty(salutation))
{
whereClause = "Salutation = @salutation";
command.Parameters.AddWithValue("@salutation", salutation);
}
else whereClause = "Salutation is null";
command.CommandText = "select * from People where " + whereClause;
Is there a more correct way?
I would probably avoid concatenation to build your where clause. You could change you sql to the following. May open your self up for SQL Injections attacks.