Reputation: 10570
I know this question was asked many times, but i am not able to find a solution for it
This is my code
string query = @"SELECT *
FROM SMSMessage
WHERE (respondCode IS @respondCode)
and (sentOn > '08/26/2016')
";
//string query = "select * from SMSMessage";
SqlConnection con = new SqlConnection(Utilities.getConnectionString());
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@respondCode", DBNull.Value);
I want the responseCode to be null,
I am getting error:
syntax error near @responseCode
when I do this responseCode is NULL
, there is no syntax error, but the query for some reaonse doesn't bring any result
Help please
Upvotes: 0
Views: 226
Reputation: 216273
I would use directly IS NULL and not passing any parameter, but the most important change is how do you apply the date constant in your query statement.
Assuming you use the Italian locale in your sql server database I would use
string query = @"SELECT * SMSMessage
WHERE respondCode IS NULL
AND (sentOn > CONVERT(DateTime, '26/08/2016', 105))
On the contrary I would look carefully to the value passed for the sentOn condition. If this value changes dynamically it is better to use a parameter for this value. In this way the query optimizer of sql server will be able to build a better (faster) execution plan
string query = @"SELECT * SMSMessage
WHERE respondCode IS NULL
AND sentOn > @dateLimit";
SqlConnection con = new SqlConnection(Utilities.getConnectionString());
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("@dateLimit", SqlDbType.DateTime).Value = new DateTime(2016, 8, 26);
Upvotes: 2
Reputation: 93694
I guess you want this
Where (respondCode = @respondCode or @respondCode is null)
and sentOn > '08/26/2016'
When a value is passed to @respondCode
parameter the records will be filter based on @respondCode
and sentOn > '08/26/2016'
.
When nothing is passed to @respondCode
parameter (ie) NULL
, then records will be filtered only based on sentOn > '08/26/2016'
As mentioned in comments by Steve, If you need records only when respondCode
is NULL
then no need of that variable just hardcode the NULL
condition in Where
clause
Where respondCode is null
and sentOn > '08/26/2016'
Upvotes: 1