Keys Append Method, Key Type, RelatedColumn, RelatedTable and UpdateRule Properties Example (VB)

The following code demonstrates how to create a new foreign key relationship between two existing tables named Customers and Orders.

' BeginCreateKeyVB  
Sub Main()  
    On Error GoTo CreateKeyError  
    Dim kyForeign As New ADOX.Key  
    Dim cat As New ADOX.Catalog  
    ' Connect to the catalog.  
    cat.ActiveConnection = "Provider='Microsoft.Jet.OLEDB.4.0';" & _  
        "Data Source='Northwind.mdb';"  
    ' Define the foreign key.  
    kyForeign.Name = "CustOrder"  
    kyForeign.Type = adKeyForeign  
    kyForeign.RelatedTable = "Customers"  
    kyForeign.Columns.Append "CustomerId"  
    kyForeign.Columns("CustomerId").RelatedColumn = "CustomerId"  
    kyForeign.UpdateRule = adRICascade  
    ' Append the foreign key to the keys collection.  
    cat.Tables("Orders").Keys.Append kyForeign  
    'Delete the key t demonstrate the Delete method.  
    cat.Tables("Orders").Keys.Delete kyForeign.Name  
    'Clean up.  
    Set cat.ActiveConnection = Nothing  
    Set cat = Nothing  
    Set kyForeign = Nothing  
    Exit Sub  
    Set cat = Nothing  
    Set kyForeign = Nothing  
    If Err <> 0 Then  
        MsgBox Err.Source & "-->" & Err.Description, , "Error"  
    End If  
End Sub  
' EndCreateKeyVB  

See Also

Append Method (ADOX Columns)
Append Method (ADOX Keys)
Catalog Object (ADOX)
Column Object (ADOX)
Columns Collection (ADOX)
Key Object (ADOX)
Keys Collection (ADOX)
Name Property (ADOX)
RelatedColumn Property (ADOX)
RelatedTable Property (ADOX)
Table Object (ADOX)
Tables Collection (ADOX)
Type Property (Key) (ADOX)
UpdateRule Property (ADOX)