1

我已经尝试了几种方法来完成这项工作,但我一直收到同样的错误。我正在尝试删除 tblList 中的 lisDate 列(其类型为 DateTime)等于日期(没有时间)的行。假设日期是 14/07/2012(2012 年 7 月 14 日),并且 dbConnection 是一个开放的 OleDbConnection:

string dt = string.Format("{0}/{1}/{2}", 14, 07, 2012);
OleDbCommand command = new OleDbCommand("DELETE FROM tblList WHERE CAST(lisDate as DATE) = #" + dt + "#", dbConnection);
command.ExecuteNonQuery();

这给出了以下错误:

查询表达式“CAST(lisDate as DATE) = #14/07/2012#”中的语法错误(缺少运算符)。

这可能是一个愚蠢的问题,因为我以前从未比较过 DateTime 值,但我会感谢您的帮助。谢谢!

4

2 回答 2

0

我没有方便的 Access,但在 SQL 中,你有错误的代码。我会尝试这样的事情作为你的查询字符串:

"delete from tbllist where
cast(lisDate as varchar(9)) = '" +dt +"'"

实际上,更好的是:

"delete from tbllist
where datepart(mm,lisDate) = '07' and
datepart(dd,lisDate) = '14' and
datepart(yy,lisDate = '2012'  -- obviously cancatinating in your values
于 2012-11-15T15:07:49.393 回答
0

尝试使用参数,它将提供隐式日期转换:

        string dt = string.Format("{0}/{1}/{2}", 14, 07, 2012);
        OleDbCommand command = new OleDbCommand("DELETE FROM tblList WHERE lisDate = [pDate]", dbConnection);
        OleDbParameter dateParm = command.Parameters.Add("pDate", OleDbType.Date);
        dateParm.Value = dt;
        command.ExecuteNonQuery();

修订:

一个更完整的解决方案结合了 Chris Dunaway 对支持日期和时间的精辟评论,如下所示:

    void DeleteByDate()
    {
        try
        {
            using (OleDbConnection dbConnection = new OleDbConnection())
            {
                dbConnection.ConnectionString = myConnectionString;
                dbConnection.Open();
                string dt = string.Format("{0}/{1}/{2}", 14, 07, 2012);
                using (OleDbCommand command = new OleDbCommand("DELETE FROM tblList WHERE lisDate = [pDate]", dbConnection))
                {
                    OleDbParameter dateParm = command.Parameters.Add("pDate", OleDbType.DBTimeStamp);
                    dateParm.Value = dt;
                    command.ExecuteNonQuery();
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
于 2012-11-15T15:17:08.217 回答