从表中删除记录实际上并不是删除VBA Access

时间:2017-10-25 22:29:53

标签: vba ms-access access-vba

我有一个名为Scenarios的表,与ESDNode有1对多的关系。可以有多个ESDN代码引用单个场景。

对于每个场景,必须至少有一个ESDNode,这意味着当要删除场景时,必须删除其所有相关的ESDNode。

因此,当用户选择一个场景并尝试删除它时,会调用此函数:

Private Sub Form_Delete(Cancel As Integer)
  Dim scenID As Long
  Dim ESDHeadNodeID As Long
  Dim response As Long
  Dim style As Long

  scenID = Forms!Main!Scenarios!ScenarioID
  ESDHeadNodeID = DLookup("ESDNodeID", "ESDNodes", "((ESDNodes.ESDNodeType)=1) AND ((ESDNodes.ScenarioID) = " & scenID & ")")

  style = vbYesNoCancel + vbQuestion
  response = MsgBox("Are you sure you wish to delete all selected nodes and their children?", style)
  If response = vbYes Then
     DeleteESDChildren (ESDHeadNodeID)
     loadESDTreeView
  End If
End Sub

在DeleteESDChildren中,我处理删除所有相关的ESDNode。我删除了与此函数中的错误无关的所有代码。 这是函数:

Public Function DeleteESDChildren(lngID As Long)
  Dim rst_Del As Recordset
  Set rst_Del = CurrentDb.OpenRecordset("SELECT * FROM ESDNodes WHERE ESDNodeID = " & lngID)

  rst_Del.MoveFirst

  'Delete the head node
  If Not rst_Del.EOF Then
     rst_Del.Delete 
  End If
End Function

我用最简单的情况测试了这段代码,其中一个场景只有一个ESDNode,而ESDNode没有子节点。调用rst_Del.Delete的行,我希望删除这个单一的ESDNode。但是当Form_Delete尝试结束Sub声明时,我得到一个错误"由于表格' ESDNodes'无法删除或更改记录。包括相关记录。"所以这个单一的ESDNode不会被删除。

显示我的表之间关系的屏幕截图 Screenshot showing the relationships between my tables

2 个答案:

答案 0 :(得分:1)

这可以使用SQL

来实现
CurrentDb.Execute "DELETE * FROM ESDNodes WHERE ESDNodeID = " & lngID

答案 1 :(得分:0)

看起来你已经处于循环中。

Public Function DeleteESDChildren(lngID As Long)
    Dim rst As Recordset
    'find the children of the node
    Set rst = CurrentDb.OpenRecordset("SELECT * FROM ESDNodes WHERE ParentID = " & lngID)

    'call deletechildren on each child in turn
    While Not rst.EOF
        DeleteESDChildren (rst!ESDNodeID) '<-- goes back to the beginning.
        rst.MoveNext
    Wend
    etc.