primary key

W

Wilson

Friends,

Which command returns the name of the primary key field of a table in Access
databaser?

wilson
 
A

Allen Browne

Wilson, there's a bit more to it than that. The primary key is actually an
index, and it can be a combination of fields.

The code below shows how to iterate through the indexes of a table, testing
the Primary property to see if it is the primary key, and then listing the
fields that make up the index, along with a description.

Function ShowIndexes(strTable As String)
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim ind As DAO.Index
Dim fld As DAO.Field

Set db = CurrentDb()
Set tdf = db.TableDefs(strTable)
For Each ind In tdf.Indexes
Debug.Print ind.Name, IndexDescrip(ind)
Debug.Print " Field(s): ";
For Each fld In ind.Fields
Debug.Print fld.Name;
Next
Debug.Print
Debug.Print " " & IndexDescrip(ind)
Debug.Print
Next

Set ind = Nothing
Set tdf = Nothing
Set db = Nothing
End Function

Function IndexDescrip(ind As DAO.Index) As String
'Purpose: Return a string describing the characteristics of the index.
Dim strOut As String 'String to concatenate to.
Const strcSep = ", " 'Separator between items.

If ind.Primary Then
strOut = strOut & "Primary" & strcSep
End If

If ind.Foreign Then
strOut = strOut & "Foreign" & strcSep
End If

If ind.Clustered Then
strOut = strOut & "Clustered" & strcSep
End If

If ind.Unique Then
strOut = strOut & "Unique" & strcSep
End If

If ind.Required Then
strOut = strOut & "Required" & strcSep
End If

If ind.IgnoreNulls Then
strOut = strOut & "Ignore nulls" & strcSep
End If

'Return the string without the trailing separator.
If strOut <> vbNullString Then
IndexDescrip = Left$(strOut, Len(strOut) - Len(strcSep))
End If
End Function
 
Top