简体   繁体   English

如何在 Access SQL 中使用 BETWEEN 和 AND 来过滤日期范围?

[英]How do I use BETWEEN and AND in Access SQL to filter on a date range?

I am using an Access database that has table Visits with field VisitDate whose values are stored as a strings (eg 01/21/2020 ).我正在使用一个 Access 数据库,该数据库具有带有字段VisitDate的表Visits ,其值存储为字符串(例如01/21/2020 )。 I need to extract all records using VisitDate fields values between 1/20/2020 and 1/26/2020 .我需要提取使用的所有记录VisitDate之间字段的值1/20/20201/26/2020 The best I can do, after working on this problem for that last five days is...在过去五天解决这个问题之后,我能做的最好的是......

dim WHEREclause as string = " WHERE VisitDate BETWEEN " & ccc & " AND " & ddd

where ccc is "01/20/2020" and ddd is "01/26/2020" .其中ccc"01/20/2020"并且ddd"01/26/2020" This gives me the correct records for year 2020, but it also return records from the same time period in 2019. How do I fix this problem?这为我提供了 2020 年的正确记录,但它也返回了 2019 年同一时间段的记录。我该如何解决这个问题?

Combining the comments by @LarsTech and @jmcilhinney.结合@LarsTech 和@jmcilhinney 的评论。 Use parameters and Convert the string field to a real date.使用参数并将字符串字段转换为真实日期。

Private Sub OPCode(ccc As String, ddd As String)
    Dim dt As New DataTable
    Using cn As New OleDbConnection("Your connection string"),
    cmd As New OleDbCommand("Select * From Visits WHERE CDate(VisitDate) BETWEEN @FirstDate AND @SecondDate;")
        cmd.Parameters.Add("FirstDate", OleDbType.Date).Value = CDate(ccc)
        cmd.Parameters.Add("SecondDate", OleDbType.Date).Value = CDate(ddd)
        dt.Load(cmd.ExecuteReader)
    End Using
    DataGridView1.DataSource = dt
End Sub

Please be aware that with Access, the names of the Parameters do not matter.请注意,对于 Access,参数的名称无关紧要。 It is the order that the parameters appear in the sql statement must match the order that the parameters are added to the Parameters collection.它是参数在sql语句中出现的顺序必须与参数添加到Parameters集合中的顺序相匹配。 I use descriptive names for readability.我使用描述性名称来提高可读性。

Do it with #用#来做

dim WHEREclause as string = " WHERE VisitDate BETWEEN #" & ccc & "# AND #" & ddd & "#"

nb: beware of concatenating string, it facilitates sql injections注意:注意连接字符串,它有助于 sql 注入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM