【问题标题】:How can I create one form in Access 2010 to insert records into two related tables?如何在 Access 2010 中创建一个表单以将记录插入两个相关表?
【发布时间】:2015-02-02 22:23:17
【问题描述】:

我有三个表:一个父表和两个子表。这两个子表与父表是一对一的关系。之所以采用这种结构,是因为这两个子表有一些共同特点,但也有不同之处。我想要完成的是避免直接进入父表并为子表提供表单,然后这些表单也会填充父表中的字段(子表本身不存在的字段)。

附:我是 Access 2010 的新手。

【问题讨论】:

  • 按照你定义的关系,父母只能有一个孩子?为什么会这样?您应该将两张表合二为一。创建主窗体子窗体设置以输入数据。这样没有父母就没有孩子。

标签: ms-access ms-access-2010


【解决方案1】:

这很容易做到。 我将展示 1 个孩子的情况。然后可以多次复制 让我们假设这个结构

父表

  • IDParent -->键
  • PField1
  • PField2 ...

子表

  • IDChild1 -->键
  • CField1
  • CField2
  • ...
  • Parent_ID --> 链接到 Parent 表(IDParent)

通过IDParent-->Parent_ID建立Parent和child的关系。

这是管理记录添加的代码。 在子窗体的 AfterInsert 事件中,您可以输入这样的代码

Private Sub Form_AfterInsert()
  Dim rsParent As DAO.Recordset
  Dim lngParentID As Long

  '
  ' Creates a recordset from Parent table
  '
  set rsParent = CurrentDb.OpenRecordset("SELECT * FROM tbParent",dbOpenDynaset)                    

  ' Creates a new record in parent table
  With rsParent  
      .AddNew
      .Fields("PField1") = ...              ' Populate fields here
      .Fields("PField2") = ...
      .Update

  End With

  rsParent.MoveLast
  lngParentID = rs.Fields("IDParent)        ' Get IDParent of recently added parent record

  rsParent.Close                            ' Close recordset

  Me.Parent_ID = lngParentID                ' Assign to current record inserted in child table the link to parent record just created  

  Me.Requery                                ' Refresh recordset under child form

End Sub

让我知道这是否是您要找的。

再见, 巫师

【讨论】:

    【解决方案2】:

    您可以通过 VBA 代码来完成,也可以设置适当的关系(数据库关系),以便信息自动更新。

    您需要确保所有表都具有将表相互关联的主键,否则没有可用于更新表的参考点。

    您可能需要查看the MS KB article,并密切关注关于执行引用完整性的部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多