我将日期作为 "09/10/2014" 添加到文本框中并单击提交按钮但出现错误:-
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value error.
下面是我在调试时生成的查询:-
select * from WMS_BIN_STATUS_TRACK where 1!=1 or Current_Item_Exp_Dt = convert(datetime, '09/10/2014', 103)
下面是完整的代码:-
protected void btnTrack_OnClick(Object sender, EventArgs e)
{
string whereClause = "1!=1";
if (ddlBin.SelectedValue != "0")
{
whereClause = whereClause + "or location_name='" + ddlBin.SelectedValue + "'";
}
if (ddlItem.SelectedValue != "0")
{
whereClause = whereClause + "or Current_Item_code='" + ddlItem.SelectedValue + "'";
}
if (txtBatch.Text != "")
{
whereClause = whereClause
+ " or Current_Item_Batch " + (ddlmathsign.SelectedValue == "Equal" ? (" = '" + txtBatch.Text + "'") : (" like '%" + txtBatch.Text + "%'"));
}
if (txtExpCal.Value != "")
{
whereClause = whereClause + "or Current_Item_Exp_Dt " + (ddlAssignvalue.SelectedValue == "Greater than" ? ">" : (ddlAssignvalue.SelectedValue == "Less than" ? "<" :
(ddlAssignvalue.SelectedValue == "Equal to" ? "=" : (ddlAssignvalue.SelectedValue == "Greater than equal to" ? ">=" : "<=")))) + "convert(datetime, '" + txtExpCal.Value + "', 103)";
}
if (ddlBin.SelectedValue == "0" && ddlItem.SelectedValue == "0" && txtBatch.Text == "" && txtExpCal.Value == "")
{
BindGrid();
}
else
{
string query = "select * from WMS_BIN_STATUS_TRACK where " + whereClause;
SqlDataAdapter da = new SqlDataAdapter(query, strConnString);
DataTable dt = new DataTable();
da.Fill(dt);
GrdBinStockTracker.DataSource = dt;
GrdBinStockTracker.DataBind();
}
}
注意 由于我在本地条件下工作只是为了测试,SQL 注入(inject)在这里不是问题。
此外,这是与不同日期时间相关的问题吗? ?
请您参考如下方法:
因为您的列是 varchar 并且无法更改为 datetime 您还需要将该列转换为条件的日期时间。
请检查以下查询
whereClause = whereClause + "or convert(datetime,Current_Item_Exp_Dt,103) "
+ (ddlAssignvalue.SelectedValue == "Greater than" ? ">" :
(ddlAssignvalue.SelectedValue == "Less than" ? "<" :
(ddlAssignvalue.SelectedValue == "Equal to" ? "=" :
(ddlAssignvalue.SelectedValue == "Greater than equal to" ? ">=" : "<=")))) +
"convert(datetime, '" + txtExpCal.Value + "', 103)";
If you are not sure Current_Item_Exp_Dt always contain a valid date you can use below query build as per DarkNight
whereClause = whereClause + "or (CASE WHEN ISDATE(Current_Item_Exp_Dt)=1
THEN convert(datetime,Current_Item_Exp_Dt,103) ELSE NULL END) "
+ (ddlAssignvalue.SelectedValue == "Greater than" ? ">" :
(ddlAssignvalue.SelectedValue == "Less than" ? "<" :
(ddlAssignvalue.SelectedValue == "Equal to" ? "=" :
(ddlAssignvalue.SelectedValue == "Greater than equal to" ? ">=" : "<=")))) +
"convert(datetime, '" + txtExpCal.Value + "', 103)";
