I'm running a query with a couple date constraints. If I execute the code below with the dates hardcoded and no parameters, I get a result I expect (a simple integer). However, when I try to use parameters I get an empty result set. No errors, just no results.
log("Connecting to SQL Server...");
string connectionString = "DSN=HSBUSTEST32;";
string queryString = "SELECT COUNT(*) FROM Table WHERE myDateTime >= '?' AND myDateTime < '?'";
//string queryString = "SELECT COUNT(*) FROM Table WHERE myDateTime >= '@startDate' AND myDateTime < '@endDate'";
string startDate = "2016-08-23";
string endDate = "2016-08-24";
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
OdbcCommand command = new OdbcCommand(queryString, connection);
command.Parameters.AddWithValue("startDate",startDate);
command.Parameters.AddWithValue("endDate", endDate);
//command.Parameters.Add("startDate", OdbcType.VarChar).Value = "2016-08-23";
//command.Parameters.Add("endDate", OdbcType.VarChar).Value = "2016-08-24";
try
{
connection.Open();
OdbcDataReader reader = command.ExecuteReader();
while (reader.Read())
{
log(reader[0].ToString());
}
reader.Close();
}
catch (Exception ex)
{
log(ex.Message);
}
}
As you can see I've tried both named parameters as well as using the ?
placeholder. I've also tried a couple different methods of adding the parameters, Add()
and AddWithValue()
, though truthfully I don't understand the difference.
What is causing the empty results?