如何在后端数据库,VBA,Access中删除SQL记录

时间:2019-01-22 13:39:14

标签: vba ms-access

我想删除后端(离线)数据库中的CUSTOMER表中“ pathway”字段中的所有记录。

到目前为止,我有这个功能,但是它不适用于DELETE语句

Sub delpath()

Dim dbinputC As String

dbinputC = "[" & Application.CurrentProject.Path & "\CUSTOMER.accdb" & "]"

DoCmd.RunSQL "DELETE pathway FROM " & dbinputC & ".SPECPATH (WHERE pathway <> Null);"

End Sub

Dim dbinputC As String

dbinputC = "'" & Application.CurrentProject.Path & "\CUSTOMER.accdb" & "'"
DoCmd.RunSQL "DELETE pathway FROM SPECPATH (WHERE pathway <> Null) IN " & dbinputC & ";"

3 个答案:

答案 0 :(得分:1)

 Private Sub Test_Clear_Data
     Clear_Data "SPECPATH", "Pathway"
 End Sub


 Private Sub Clear_Data(Table_Name as String, Column_Name As String)
 Dim Connection_Path As String
 Dim Source_Recset As Object
 'Assumes "Clear_Data_Query" already exists
   Set Source_Recset = CurrentDB.QueryDefs("Clear_Data_Query")
   Source_Recset.SQL = CStr("Update " & Table_Name & " SET [" & Table_Name & "].[" & Column_Name & "] = NULL WHERE [" & Table_Name & "].[" & Column_Name & "] IS NOT Null" & ";")
   Source_Recset.Execute
   Source_Recset.Close
End Sub

Source_Recset.SQL应该获得“ UPDATE SPECPATH SET [SPECPATH]。[Pathway] = NULL其中[SPECPATH]。[Pathway]不为空;”如果表是SPECPATH并且列名是Pathway 由于您引用的是脱机数据库,因此我包含了用于临时添加表并在之后将其删除的代码(如果您将表保留在访问文件中,则无需使用代码

Private Sub Clear_Offline_Data(Share_Folder as String, File_Name as String, Table_Name as String, Column_Name As String)
Dim Connection_Path As String
Dim Source_Recset As Object
Dim Destination_Recset As Object

'Create Table To Network Data
   Set Destination_Recset = currentDB.CreateTableDef("Offline_Data_Table")
   Connection_Path = ";DATABASE=" & ShareFolder & "\" & File_Name
   Destination_Recset.Connect = Connection_Path
   Destination_Recset.SourceTableName = Table_Name

   currentDB.TableDefs.Append Destination_Recset
   currentDB.TableDefs.Refresh
'Create Temp_Data From Network Table
   Set Source_Recset = CurrentDB.CreateQueryDef("Clear_Data_Query")
   Source_Recset.SQL = CStr("Update Offline_Data_Table SET [Offline_Data_Table]." & Column_Name & " = NULL WHERE [Offline_Data_Table]." & Column_Name & " IS NOT Null" & ";")
   Source_Recset.Execute
   Source_Recset.Close
'Remove Table to network data 
   currentDB.TableDefs.Delete "Offline_Data_Table"
   currentDB.TableDefs.Refresh
'Remove Query
   currentDB.QueryDefs.Delete "Clear_Data_Query"
   currentDB.QueryDefs.Refresh
End Sub

答案 1 :(得分:0)

删除查询将删除行,而不是字段。

您必须使用 update 查询来更新字段路径。

答案 2 :(得分:0)

我想它毕竟可以工作:

Sub delpath()

Dim dbinputC As String

 dbinputC = "[" & Application.CurrentProject.Path & "\CUSTOMER.accdb" & "]"
 DoCmd.RunSQL "DELETE pathway FROM " & dbinputC & ".SPECPATH WHERE pathway Is Not Null;"

 End Sub