现在的位置: 首页 > 综合 > 正文

VBA Brush Up 12:Setting Up Indexes and Table Relationships with ADO

2013年08月03日 ⁄ 综合 ⁄ 共 6025字 ⁄ 字号 评论关闭
Technorati 标签: ,,,,

来自:Julitta Korol, "Access.2003.Programming.by.Example.with.VBA.XML.and.ASP", by Wordware Publishing, Inc. 2005, p212-p220

(1)A primary key is an index with its Unique and PrimaryKey properties set to True. There can be only one primary key per table. A primary key uniquely identifies a row in a table.

To create new keys, use the Key object from the ADOX library. To determine whether the key is primary, foreign, or unique, use the Key object’s Type property. For example, to create a primary key, set the Key object’s Type property to adKeyPrimary.

(2)

  1. Sub Create_PrimaryKey()
  2.     Dim cat As New ADOX.Catalog 
  3.     Dim myTbl As New ADOX.Table 
  4.     Dim pKey As New ADOX.Key
  5.     On Error GoTo ErrorHandler
  6.     cat.ActiveConnection = CurrentProject.Connection 
  7.     Set myTbl = cat.Tables("tblFilters"
  8.     With pKey 
  9.         .Name = "PrimaryKey" 
  10.         .Type = adKeyPrimary 
  11.     End With 
  12.     pKey.Columns.Append "Id" 
  13.     myTbl.Keys.Append pKey 
  14.     Set cat = Nothing 
  15.     Exit Sub
  16. ErrorHandler: 
  17.     If Err.Number = -2147217856 Then 
  18.         MsgBox "The 'tblFilters' is open.", _ 
  19.             vbCritical, "Please close the table" 
  20.     ElseIf Err.Number = -2147217767 Then 
  21.         myTbl.Keys.Delete pKey.Name 
  22.         Resume 
  23.     Else 
  24.         MsgBox Err.Number & ": " & Err.Description 
  25.     End If
  26. End Sub

(3)Creating a Single-Field Index:Before creating an index, make sure the table is not open and that it does not already contain an index with the same name. To define an index, perform the following:

  • Append one or more columns to the index by using the Append method.
  • Set the Name property of the Index object and define other index properties, if necessary.
  • Use the Append method to add the Index object to the table’s Indexes collection.

You can use the Unique property of the Index object to specify whether the index keys must be unique. The default value of the Unique property is False.  Another property, IndexNulls, lets you specify whether Null values are allowed in the index. This property can have one of the constants shown in Table 12-1.

intrinsic constants for the IndexNulls

(4)

  1. Sub Add_SingleFieldIndex()
  2.     Dim cat As New ADOX.Catalog 
  3.     Dim myTbl As New ADOX.Table 
  4.     Dim myIdx As New ADOX.Index 
  5.     On Error GoTo ErrorHandler
  6.     cat.ActiveConnection = CurrentProject.Connection 
  7.     Set myTbl = cat.Tables("tblFilters"
  8.     With myIdx 
  9.         .Name = "idxDescription" 
  10.         .Unique = False 
  11.         .IndexNulls = adIndexNullsIgnore 
  12.         .Columns.Append "Description" 
  13.         .Columns(0).SortOrder = adSortAscending 
  14.     End With 
  15.     myTbl.Indexes.Append myIdx
  16.     Set cat = Nothing 
  17.     Exit Sub
  18. ErrorHandler: 
  19.     If Err.Number = -2147217856 Then 
  20.         MsgBox "The 'tblFilters' cannot be open.", vbCritical, _ 
  21.             "Close the table" 
  22.     ElseIf Err.Number = -2147217868 Then 
  23.         myTbl.Indexes.Delete myIdx.Name 
  24.         Resume 0 
  25.     Else 
  26.         MsgBox Err.Number & ": " & Err.Description 
  27.     End If
  28. End Sub 

indexes

(5)Adding a Multiple-Field Index to a Table:

  1. Sub Add_MultiFieldIndex()
  2.     Dim conn As New ADODB.Connection 
  3.     With conn 
  4.         .Provider = "Microsoft.Jet.OLEDB.4.0" 
  5.         .Open "Data Source=" & CurrentProject.Path & _ 
  6.             "/Northwind.mdb"
  7.         ' Create a multifield Index named Location on City and Region fields. 
  8.         .Execute "CREATE INDEX Location ON Employees (City, Region);" 
  9.     End With 
  10.     conn.Close 
  11.     Set conn = Nothing 
  12.     MsgBox "New index (Location) was created."
  13. End Sub

it uses the Execute method of the Connection object to run the DDL (Data Definition Language) CREATE INDEX SQL statement to add an index to the Employees table.

The CREATE INDEX statement has three parts. The name of the index to be created is followed by the keyword ON, the name of the existing table that will contain the index, and the name or names of the fields to be indexed. The field names should be listed in parentheses following the table name. The index is assumed to be ascending unless the DESC keyword is placed at the end of the CREATE INDEX statement.

(6)Listing Indexes in a Table: The Indexes collection contains all Index objects of a table. You can retrieve all the index names from the Indexes collection.

  1. Dim idx As New ADOX.Index
  2. For Each idx In tbl.Indexes 
  3.     Debug.Print idx.Name 
  4. Next idx 

(7)Deleting Table Indexes: Although you can delete unwanted or obsolete indexes from the Indexes window in the Microsoft Office Access 2003 user interface, it is much faster to remove them programmatically.

  1. Setup: 
  2.     Set tbl = cat.Tables("Employees")
  3.     Debug.Print tbl.Indexes.count 
  4.     For Each idx In tbl.Indexes 
  5.         If idx.PrimaryKey <> True Then 
  6.             tbl.Indexes.Delete (idx.Name) 
  7.             GoTo Setup 
  8.     End If 
  9.     Next idx

Notice that each time you delete an index from the table’s Indexes collection you must set the reference to the table because current settings are lost when an index is deleted. Hence, the GoTo Setup statement sends Visual Basic to the Setup label to get the new reference to the Table object.

(8)Creating Table Relationships: To establish a one-to-many relationship between tables, perform the following steps:

1. Use the ADOX Key object to create a foreign key and set the Type property of the Key object to adKeyForeign. A foreign key consists of one or more fields in a foreign table that uniquely identify all rows in a primary table.

2. Use the RelatedTable property to specify the name of the related table.

3. Use the Append method to add appropriate columns in the foreign table to the foreign key. A foreign table is usually located on the “many” side of a one-to-many relationship and provides a foreign key to another table in a database.

4. Set the RelatedColumn property to the name of the corresponding column in the primary table.

5. Use the Append method to add the foreign key to the Keys collection of the table containing the primary key.

(9)

tt

  1. Sub CreateTblRelation()
  2.     Dim cat As New ADOX.Catalog 
  3.     Dim fKey As New ADOX.Key 
  4.     On Error GoTo ErrorHandle
  5.     cat.ActiveConnection = CurrentProject.Connection 
  6.     With fKey 
  7.         .Name = "fkPubId" 
  8.         .Type = adKeyForeign 
  9.     .RelatedTable = "Publishers" 
  10.     .Columns.Append "PubId" 
  11.     .Columns("PubId").RelatedColumn = "PubId" 
  12.     End With 
  13.     cat.Tables("Titles").Keys.Append fKey
  14.     MsgBox "Relationship was created." 
  15.     Set cat = Nothing 
  16.     Exit Sub
  17. ErrorHandle: 
  18.     cat.Tables("Titles").Keys.Delete "fkPubId" 
  19.     Resume
  20. End Sub

tt

(10)Chapter Summary: In this short chapter you acquired programming skills that enable you to create keys (primary keys and indexes) in Microsoft Access tables. You also learned how to use ADOX to establish a one-to-many relationship between tables.

抱歉!评论已关闭.