gpt4 book ai didi

vba - 微软 Access : Date format for SQL Insert using VBA

转载 作者:行者123 更新时间:2023-12-02 04:13:00 31 4
gpt4 key购买 nike

这可能是一个非常简单的问题,但到目前为止,我很难理解我在网上找到的信息。当我尝试从我的 VBA 中运行 SQl 时,它给我的 strSQl 类型不匹配。

我有一个包含 4 列的表 [tbl_DatabaseUpdateLog]

UpdateID (Autonumber)

Start (Date/Time)

End (Date/Time)

Duration (Date/Time)

我必须定期从公司数据库中提取信息以用于较小的分析项目,并且我想记录运行这些查询的频率和时间。每次开始更新时,它都会运行以下命令:

Dim StartUpdate, EndUpdate, LengthUpdate, strSQl As Date
StartUpdate = Time()

Call UpdateAll 'This calls the collection of queries and is irrelevant for my problem

EndUpdate = Time()
LengthUpdate = EndUpdate - StartUpdate
Forms!frm_Timer.Caption = "Update Completed at " & EndUpdate & " (" & Format(LengthUpdate, "HH:MM:SS") & ")"

DoCmd.SetWarnings (0)
strSQl = "INSERT INTO tbl_DatabaseUpdateLog ( Start, [End], Duration ) " & _
"SELECT '" & StartUpdate & "' AS Started, '" & EndUpdate & "' AS Ended, '" & LengthUpdate & "' AS Lasted"
DoCmd.RunSQL strSQl
DoCmd.SetWarnings (-1)

DoCmd.Close acForm, Me.Name

我曾尝试在日期前后使用#,并使用 Now() 而不是 Time(),但我觉得我缺少一个基本概念来帮助我解决问题。如果有帮助,我只需要一天中的时间和持续时间(与其说是日期本身)。

最佳答案

When I try to run SQl from within my VBA, it gives me a type mismatch on my strSQl

检查这 2 个语句 ...

Dim StartUpdate, EndUpdate, LengthUpdate, strSQl As Date
strSQl = "INSERT INTO tbl_DatabaseUpdateLog ( Start, [End], Duration ) " & _
"SELECT '" & StartUpdate & "' AS Started, '" & EndUpdate & "' AS Ended, '" & LengthUpdate & "' AS Lasted"

当您声明 strSQl As Date 时,这意味着 strSQl 只能保存日期/时间值。诸如 "INSERT INTO ... whatever" 之类的字符串不是日期/时间值。因此,当您尝试将这样的字符串存储到 strSQl 时,Access 会提示数据类型不兼容:“类型不匹配”

由于您打算 strSQl 保存 SQL 语句的文本,因此以这种方式声明它(而不是 As Date):Dim strSQl As String

该更改应该可以让您克服错误。为了您更大的目标,使用带有 DAO 的参数查询。

Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim StartUpdate As Date, EndUpdate As Date, LengthUpdate As Date
Dim strSQl As String

StartUpdate = Time()
Call UpdateAll 'This calls the collection of queries and is irrelevant for my problem
EndUpdate = Time()

LengthUpdate = EndUpdate - StartUpdate
Forms!frm_Timer.Caption = "Update Completed at " & EndUpdate & " (" & Format(LengthUpdate, "HH:MM:SS") & ")"

strSQl = "INSERT INTO tbl_DatabaseUpdateLog ([Start], [End], Duration) " & _
"VALUES ([p1], [p2], [p3]);"
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strSQl)
With qdf
.Parameters("p1").Value = StartUpdate
.Parameters("p2").Value = EndUpdate
.Parameters("p3").Value = LengthUpdate
End With
qdf.Execute dbFailOnError
DoCmd.Close acForm, Me.Name

请注意,对于 INSERT,使用这种方法,日期格式 甚至都不是问题。由于 StartUpdateEndUpdateLengthUpdate 都是有效的日期/时间值,您可以简单地将它们提供给参数,而无需担心格式和# 分隔符。

关于vba - 微软 Access : Date format for SQL Insert using VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35470311/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com