如何搜索小于或大于X的日期

时间:2014-07-26 00:11:34

标签: c# asp.net sql

这是我用来创建按日期范围过滤的自定义报告的代码。第一个标准工作正常,但第二个和第三个标准没有。它会引发语法错误。谁能告诉我为什么?

string cmd = "SELECT PURCHASE_ORDER.cid, PURCHASE_ORDER.deptid, PURCHASE_ORDER.procid, PURCHASE_ORDER.purchase_order_no, PURCHASE_ORDER.requesition_no, PURCHASE_ORDER.contract_no, PURCHASE_ORDER.purchase_order_date, COMPANY.company_name,  DEPARTMENT.department_name, PROCUREMENT_METH.method FROM PURCHASE_ORDER INNER JOIN PROCUREMENT_METH ON PURCHASE_ORDER.procid = PROCUREMENT_METH.procid INNER JOIN COMPANY ON PURCHASE_ORDER.cid = COMPANY.cid INNER JOIN DEPARTMENT ON PURCHASE_ORDER.deptid = DEPARTMENT.deptid WHERE PURCHASE_ORDER.deptid = DEPARTMENT.deptid";

// Check Criteras
if (!string.IsNullOrWhiteSpace(ddlDepartment.Text) && !ddlDepartment.Text.Equals("0"))
   cmd += " AND PURCHASE_ORDER.deptid LIKE '%" + ddlDepartment.Text + "%' ";

if (!string.IsNullOrWhiteSpace(txtfromdate.Text))
   cmd += "AND PURCHASE_ORDER.purchase_order_date '<" + txtfromdate.Text + "' ";

if (!string.IsNullOrWhiteSpace(txttodate.Text))
   cmd += "AND PURCHASE_ORDER.purchase_order_date '<" + txttodate.Text + "' ";

3 个答案:

答案 0 :(得分:4)

真正有助于实际读取生成的SQL,并实际读取语法错误消息。

让我们说txttodate.Text给出价值&#34; 25-Jul-2014&#34;。以下是您的代码为此生成的内容:

AND PURCHASE_ORDER.purchase_order_date '<25-Jul-2014'

SQL Server在这种情况下生成错误消息:

  

错误102:&#39;&lt; 25-Jul-2014&#39;附近的语法不正确。

那是因为你的<在字符串里面。请尝试这种方式,它会更好地

cmd += "AND PURCHASE_ORDER.purchase_order_date < '" + txttodate.Text + "' ";

虽然我们正在讨论如何改善这一点,但请使用parameters

答案 1 :(得分:2)

如果purchase_order_date数据库字段的类型为DATETIME,那么您需要将文本框的内容解析为C#Date对象,然后将ToString() Date对象解析为SQL标准日期格式。

<强>初步:

DateTime time = DateTime.Parse(txttodate.Text.Trim().Replace("'","''"));
cmd += "AND PURCHASE_ORDER.purchase_order_date '<" + datetime.ToString("yyyy-MM-dd") + "' ";

<强>更好的:

DateTime dateTime,dateTime2;

if (DateTime.TryParse(txttodate.Text.Trim().Replace("'","''"), out dateTime1) && DateTime.TryParse(txtfromdate.Text.Trim().Replace("'","''"), out dateTime2))
{
    cmd += "AND PURCHASE_ORDER.purchase_order_date BETWEEN + '" + dateTime1.ToString("yyyy-MM-dd") + "' AND '" + dateTime2.ToString("yyyy-MM-dd") + "'";
}

此外,我认为您可能希望使用BETWEEN SQL运算符来确定FROM日期和TO日期之间的任何purchase_order_dates

答案 2 :(得分:-1)

我修好了。

后出现问题
cmd += "AND PURCHASE_ORDER.purchase_order_date '<" + txtfromdate.Text + "'
像这样:

cmd += " AND PURCHASE_ORDER.purchase_order_date <'" + txtfromdate.Text + "'