"Data type mismatch in criteria expression" 当根据用户输入构建 SQL 语句时

"Data type mismatch in criteria expression" when building SQL statement from user input

我正在尝试使用 ASP Classic 将用户输入的日期与存储在 Access 数据库中的日期进行比较。

用户输入日期(SearchedStartDate),通过表单提交,然后我的SQL语句应该select记录开始日期字段比用户输入的日期。

Access数据库字段是Date/Time数据类型,我的SQL语句是这样的:

SELECT SessionID, StartDate 
FROM   SessionTable 
WHERE  StartDate>='"&SearchedStartDate&"' 
ORDER BY StartDate DESC"

我四处搜索并尝试了很多不同的方法,例如在访问日期前后使用 # 符号,以及 SearchedStartDate = FormatDateTime(SearchedStartDate, vbShortDate),但我的所有尝试都导致 "Data type mismatch in criteria expression" 错误。

我怎样才能让它工作?

应该这样写:

"SELECT SessionID, StartDate 
FROM   SessionTable 
WHERE  StartDate >= #" & SearchedStartDate & "# 
ORDER BY StartDate DESC"

其中 SearchedStartDate 应该是 yyyy/mm/dd 格式的字符串来表示您的日期值。如果格式可用,您可以这样做:

SearchedStartDate = Format(YourDateValue, "yyyy\/mm\/dd")

当您 "searched around" 时,您一定已经看到动态 SQL 被广泛认为是 坏事 的警告。正确的做法是使用参数化查询,例如

Const adDBTimeStamp = 135
Const adParamInput = 1

Dim SearchedStartDate
SearchedStartDate = "2018-01-01"  ' test data

Dim cmd
Set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = con  ' currently open ADODB.Connection
cmd.CommandText = _
        "SELECT SessionID, StartDate " & _
        "FROM SessionTable " & _
        "WHERE  StartDate >= ? " & _
        "ORDER BY StartDate DESC"
cmd.Parameters.Append cmd.CreateParameter("?", _
        adDBTimeStamp, adParamInput, , CDate(SearchedStartDate))
Dim rst
Set rst = cmd.Execute  ' ADODB.Recordset
Do Until rst.EOF
    ' work with the values in the current row of the Recordset
    rst.MoveNext
Loop