I've been having trouble with a dynamic query where I receive values via querystring to be search parameters for the select query.
When it reads it has no values at all, when I look at SQL Activity monitor to see what SQL is actually passed to it. I select the query and run it on SQL server by itself and it brings back values.
I'm very confused right now, all other fields work searching except dates. I tried parameterizing the date values a lot of other ways also, but I was getting the error. "Conversion failed when converting date and/or time from character string.'"
I'm very confused right now.
I have tried to cut out as much of the code as possible for easy reading.
var queryString = this.Request.GetQueryNameValuePairs();
List<KeyValuePair<string, object>> QueryStringKeys = new List<KeyValuePair<string, object>>();
foreach (var pair in queryString)
{
QueryStringKeys.Add(new KeyValuePair<string, object>(pair.Key.ToString(), pair.Value));
}
DateTime thedates;
thedates = DateTime.ParseExact(keys.Value.ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
string tempdatestring = thedates.Year.ToString() + "-" + thedates.Month.ToString() + "-" + thedates.Day.ToString();
SqlCommand cmd = new SqlCommand("", connection);
StringBuilder QString = new StringBuilder();
StringBuilder sqlBuilder = new StringBuilder();
QString.Append(" Where @").Append(keys.Key).Append("=@" + keys.Key + "value");
cmd.Parameters.AddWithValue("@" + keys.Key, keys.Key);
cmd.Parameters.AddWithValue("@" + keys.Key + "value", "cast('" + tempdatestring + "' as datetime)");
sqlBuilder.Append("SELECT [EMP_ID],[EMP_SURNAME],[EMP_GIVENNAMES],[EMP_TITLE],[EMP_STARTDATE] from EMPLOYEES " + QString.ToString() + ")");
cmd.CommandText = sqlBuilder.ToString();
SqlDataReader test;
test = cmd.ExecuteReader();
while (test.Read())
{
//No values returned from dates searches
}
other ways I have tried to add the date.
Please also note the date field is a date field and not datetime.
cmd.Parameters.Add("@" + keys.Key + "value", SqlDbType.DateTime).Value = tempdatestring;
// -----
SqlParameter parameter = cmd.Parameters.Add("@" + keys.Key + "value", System.Data.SqlDbType.DateTime);
parameter.Value = DateTime.Parse(tempdatestring);
//------
cmd.Parameters.AddWithValue("@" + keys.Key + "value", new SqlDateTime(thedates));
//----
cmd.Parameters.AddWithValue("@" + keys.Key + "value", thedates);