VBA& SQL - 从数据库中删除日期范围

时间:2018-06-05 14:00:47

标签: sql vba date ms-access between

我正在尝试在Access数据库上创建一个选项,删除两个日期之间的所有记录。

我在下面的代码似乎并不一致。例如,如果我的数据库的日期为01/01/18到01/30/18,并且我指定的范围正好是01/01/18到01/30/18,则它可以工作并删除所有数据。

但如果我指定任何其他日期范围(如01/01 - 01/15),它将失败并且不会删除任何记录。

[交易日期]采用短文本格式而非日期,但所有条目均为MM / DD / YY。宁愿保持这种方式,除非这是问题,没有其他选择。

请让我知道我做错了什么或者能做得更好。先感谢您。

Dim trFrmDat As String
Dim trToDat As String
Dim dbsDelete As DAO.Database
Dim qdfToDelete As DAO.QueryDef
Dim countString As String
Dim count As Long

Set dbsDelete = CurrentDb
trFrmDat = InputBox("Trade Date To Be Deleted From [MM/DD/YY]:")
trToDat = InputBox("Trade Date To Be Deleted To [MM/DD/YY]:")
If Len(trFrmDat) <> 8 Or Len(trToDat) <> 8 Then
    MsgBox ("The correct date or answer has not been entered. Process Aborted.")
    Exit Sub
Else
    countString = "SELECT COUNT(PK_ID) FROM AR_Consolidated WHERE [Trade Date] BETWEEN " & trFrmDat & " AND " & trToDat & ""
    count = dbsDelete.OpenRecordset(countString).Fields(0).Value
    Set qdfToDelete = dbsDelete.CreateQueryDef("", "DELETE FROM AR_Consolidated WHERE [Trade Date] BETWEEN " & trFrmDat & " AND " & trToDat & "")
    qdfToDelete.Execute dbFailOnError
    MsgBox ("" & count & " records have been deleted from AR_Consolidated")
End If

编辑:

我最终使用了以下建议之一,但仍然存在日期格式问题,所以我承认我无法将实际字段保留为短文本。我只是注入一条改变线,一切都很完美。

    DoCmd.RunSQL "ALTER TABLE AR_Consolidated ALTER COLUMN [Trade Date] Datetime"

3 个答案:

答案 0 :(得分:0)

为了在Jet SQL中表示日期值,您需要用#包围它,这样您的SQL最终会像这样:

DELETE FROM AR_Consolidated WHERE [Trade Date] BETWEEN #01/01/18# AND #01/30/18#

请注意,通常,将字符串与用户输入组合以生成SQL语句是一个坏主意。除了与您的问题类似的问题 - 在SQL语句中正确表示日期或其他文字 - 您还可能会对SQL注入负责,其中恶意用户会插入导致代码失败或执行不需要的操作的其他SQL语句或子句。例如,用户可以将第二个参数传入以下字符串:

01/01/18 OR 1 = 1

以及生成的SQL语句:

DELETE FROM AR_Consolidated WHERE [Trade Date] BETWEEN 01/01/18 AND 01/01/18 OR 1 = 1

会删除AR_Consolidated中的所有记录。

避免这两类问题的正确方法是使用参数化查询。

Dim sql As String
sql = _
    "PARAMETERS FromDate DATETIME, TillDate DATETIME; " & _
    "DELETE FROM AR_Consolidated " & _
    "WHERE [Trade Date] BETWEEN FromDate AND TillDate"

Dim qdfToDelete As DAO.QueryDef
Set qdfToDelete = dbsToDelete.CreateQueryDef("", sql)

qdfToDelete.Parameters("FromDate") = trFromDate 
qdfToDelete.Parameters("TillDate") = trToDate 
'You may have to convert the string values to dates first

qdfToDelete.Execute dbFailOnError

答案 1 :(得分:0)

我会采用不同的方法并使用参数而不是字符串连接。

查询的SQL将是这样的:

PARAMETERS [prmDateFrom] DateTime, [prmDateTo] DateTime;
DELETE *
FROM AR_Consolidated
WHERE [Trade Date] Between [prmDateFrom] And [prmDateTo];

然后在VBA中调用我的查询:

Sub Something()

    Dim trFrmDat As String
    Dim trToDat As String

    trFrmDat = InputBox("Trade Date To Be Deleted From [MM/DD/YY]:")
    trToDat = InputBox("Trade Date To Be Deleted To [MM/DD/YY]:")

    If Len(trFrmDat) <> 8 Or Len(trToDat) <> 8 Then
        MsgBox ("The correct date or answer has not been entered. Process Aborted.")
        Exit Sub
    End If

    Dim qdf As DAO.QueryDef
    Dim count As Long

    Set qdf = CurrentDb().QueryDefs("QueryName")
    With qdf
        .Parameters("[prmDateFrom]").Value = CDate(trFrmDat)
        .Parameters("[prmDateTo]").Value = CDate(trToDat)
        .Execute dbFailOnError
        count = .RecordsAffected
    End With

    MsgBox " " & count & " records have been deleted from AR_Consolidated"

End Sub

但是,您需要将输入验证增强为具有8个字符的普通字符串,这些字符无法转换为日期会导致运行时错误。

答案 2 :(得分:0)

您可以验证输入,然后格式化值:

trFrmDat = InputBox("Trade Date To Be Deleted From [MM/DD/YY]:")
trToDat = InputBox("Trade Date To Be Deleted To [MM/DD/YY]:")

If IsDate(trFrmDat) And  IsDate(trToDat) Then
    trFrmDat = Format(CDate(trFrmDat), "yyyy\/mm\/dd")
    trToDat = Format(CDate(trToDat), "yyyy\/mm\/dd")
    countString = "SELECT COUNT(PK_ID) FROM AR_Consolidated WHERE [Trade Date] BETWEEN #" & trFrmDat & "# AND #" & trToDat & "#"
End If

和删除SQL类似。