How to show if a query based table has primary key


When creating a table or feature layer based on a query, an Object ID column may or may not be assigned to the resulting table. This sample will indicate weather or not an Object ID column has been assigned and the method used to assign it. See the help for the IQueryName2 interface for more information on the ways in which an Object ID can be assigned.

How to use

  1. Paste the code into VBA in ArcMap.
  2. Click a table or feature layer which has been created using a query.
  3. Run the sample to see if the table has an Object id column. If it has an Object id column, the method used to assign it is also shown.
[VBA]
Public Sub QueryBasedTableType()
    
    Dim pMXD As IMxDocument
    Dim pUnk As IUnknown
    Dim pDTable As IDisplayTable
    Dim pTable As ITable
    Dim pDSet As IDataset
    Dim pQName2 As IQueryName2
    Dim strReport As String
    Dim strKey As String
    Dim pFld As IField
    
    strReport = "The Object ID was generated using the following method: "
    Set pMXD = ThisDocument
    Set pUnk = pMXD.SelectedItem
    If TypeOf pUnk Is IDisplayTable Then
        Set pDTable = pMXD.SelectedItem
        Set pTable = pDTable.DisplayTable
        Set pDSet = pTable
        If TypeOf pDSet.FullName Is IQueryName2 Then
            Set pQName2 = pDSet.FullName
            If pQName2.PrimaryKey = "" Then
                If pQName2.CopyLocally Then
                    MsgBox strReport & "COPY"
                Else
                    MsgBox "There is no ObjectID column"
                End If
            Else
                strKey = pQName2.PrimaryKey
                If InStr(strKey, ",") > 0 Then
                    MsgBox strReport & "WRAPPED" & vbNewLine & "The primary key fields are: " & strKey
                Else
                    Set pFld = pTable.Fields.Field(pTable.FindField(strKey))
                    If pFld.Type = esriFieldTypeOID Then
                        MsgBox strReport & "DIRECT" & vbNewLine & "The primary key field is: " & strKey
                    Else
                        MsgBox strReport & "WRAPPED" & vbNewLine & "The primary key field is: " & strKey
                    End If
                End If
            End If
        End If
    End If
    
End Sub