Get the name of the primary key

P

Patrick B

Working with a Microsoft Access database, what is the best way to get
the name of the primary key field? I know the table name.
 
J

J L

You can use the datareader as follows:

Dim cn as New OleDbConnection(strConnectString)
Dim cmd as New OleDbCommand
Dim myReader as OleDbDataReader
Dim dt as DataTable
Dim dRow as DataRow
Dim strPrimaryKeyList as String

cn.Open()
cmd.Connection = cn
cmd.CommandText = "Select * From yourTable"
myReader = cmd.ExecuteReader(CommandBehavior.KeyInfo)
dt = myReader.GetSchemaTable()
strPrimaryKeyList = ""
For Each dRow in dt.Rows
If dRow("IsKey") then
strPrimaryKeyList += dRow("ColumnName") & vbcrlf
End If
Next
cn.Close()

When done strPrimaryKeyList holds a list of the primary key field
names.

Hope that helps,
John
(PS I typed this in adHoc so check for typos, but you should get the
idea)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top