Материал из VB Эксперт
Перейти к: навигация, поиск

Create Relation

Sub exaRelations()
    Dim db As Database
    Dim rel As Relation
    Dim fld As Field
    Set db = CurrentDb
    Set rel = db.CreateRelation("PublisherRegions", "PUBLISHERS", "SALESREGIONS")
    rel.Attributes = dbRelationUpdateCascade
    Set fld = rel.CreateField("PubID")
    fld.ForeignName = "PubID"
    rel.Fields.Append fld
    db.Relations.Append rel
End Sub

Creating a One-to-Many Relationship

Sub CreateTblRelation()
   Dim cat As New ADOX.Catalog
   Dim fKey As New ADOX.Key
   On Error GoTo ErrorHandle
   cat.ActiveConnection = CurrentProject.Connection
   With fKey
      .Name = "fkPubId"
      .Type = adKeyForeign
      .RelatedTable = "Employee"
      .Columns.Append "EmpId"
      .Columns("Id").RelatedColumn = "PubId"
   End With
   cat.Tables("vbexTable").Keys.Append fKey
   MsgBox "Relationship was created."
   Set cat = Nothing
   Exit Sub
   cat.Tables("vbexTable").Keys.Delete "fkPubId"
End Sub

Show all foreign tables from a relation

Sub ShowRelations()
    Dim db As Database
    Dim rel As Relation
    Dim strDetail As String
    Set db = CurrentDb()
    Debug.Print "Relationships:"
    For Each rel In db.Relations
        strDetail = rel.Table & " is related to " & rel.ForeignTable
        Debug.Print strDetail
End Sub