您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Access / VBA中构建SQL字符串

在Access / VBA中构建SQL字符串

我有一个时间表应用程序,其中包含一个相当复杂的未绑定的劳务交易输入表单。有很多数据验证,速率计算和其他代码。我决定使用以下内容创建我的sql插入/更新字段。

变量strsqlInsert,strsqlValues和strsqlUpdate是表单级别的字符串。

以下几行:

Call CreatesqlString("[transJobCategoryBillingTypesID]", lngJobCategoryBillingTypesID)

其次是:

If lngTransID = 0 Then
    strsql = "INSERT into Transactions (" & Mid(strsqlInsert, 3) & ") VALUES (" & Mid(strsqlValues, 3) & ")"
Else
    strsql = "UPDATE Transactions SET " & Mid(strsqlUpdate, 3) & " WHERE transID=" & lngTransID & ";"
End If

conn.Open
conn.Execute strsql, lngRecordsAffected, adCmdText

请注意,中线删除了前导“,”。lngTrans是自动编号primamy kay的值。

Sub CreatesqlString(strFieldName As String, varFieldValue As Variant, Optional blnZeroAsNull As Boolean)
'    Call CreatesqlString("[<fieldName>]", <fieldValue>)

Dim strFieldValue As String, OutputValue As Variant

    On Error GoTo tagError

    ' if 0 (zero) is supposed to be null
    If Not IsMissing(blnZeroAsNull) And blnZeroAsNull = True And varFieldValue = 0 Then
        OutputValue = "Null"
    ' if field is null, zero length or ''
    ElseIf IsNull(varFieldValue) Or Len(varFieldValue) = 0 Or varFieldValue = "''" Then
        OutputValue = "Null"
    Else
        OutputValue = varFieldValue
    End If

    ' Note that both Insert and update strings are updated as we may need the insert logic for inserting
    '    missing auto generated transactions when updating the main transaction
    ' This is an insert
    strsqlInsert = strsqlInsert & ", " & strFieldName
    strsqlValues = strsqlValues & ", " & OutputValue
    ' This is an update
    strsqlUpdate = strsqlUpdate & ", " & strFieldName & " = " & OutputValue

    On Error GoTo 0
    Exit Sub

tagError:

    Msg@R_580_2419@ "Error " & Err.Number & " (" & Err.Description & ") in procedure CreatesqlString of VBA Document Form_LabourEntry"
    Exit Sub
End Sub

我看到其他张贴者都使用Execute方法。DoCmd.Runsql的问题在于它可以忽略错误。以下任何一项将显示查询收到的任何错误消息。如果使用DAO,请使用Currentdb.Execute strsql,dbfailonerror。对于ADO,请使用CurrentProject.Connection.ExecutestrCommand,lngRecordsAffected,adCmdText然后可以删除docmd.setwarnings行。

如果要使用docmd.setwarnings,请确保将True语句也放入任何错误处理代码中。否则,以后可能会发生奇怪的事情,特别是在您使用该应用程序时。例如,如果您关闭一个对象,您将不再收到“您是否要保存所做的更改”消息。这可能意味着不需要的更改,删除添加将保存到您的MDB中。

两种方法间的性能也可能存在显着差异。一篇文章说currentdb.execute花了两秒钟,而docmd.runsql花了八秒钟。一如既往的YMMV。

Access 2022/1/1 18:44:48 有323人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶