How to specify Primary Key when using vba to create tables

泪湿孤枕 提交于 2019-12-23 18:48:13

问题


I've updated the code with the suggestion given below, which I've tested and works great, for quick reference for future users.


I'm using the below code to create linked tables without having to set up a DSN for each user, how can I specify a primary key as you would be asked if connecting manually:

Dim sConnect    As String
Dim db          As DAO.Database
Dim tdf         As DAO.TableDef

Set db = CurrentDb

Set tdf = db.CreateTableDef
tdf.Name = "dbo_vwFeedback" ' - -- --- This is the Label that you see in Access...
tdf.Connect = "ODBC;DRIVER=SQL Server;SERVER=server01\serverinstance;DATABASE=db_name;Trusted_Connection=Yes"
tdf.SourceTableName = "vwFeedback" ' - -- --- This is the actual name in SQL Server, minus the owner.
db.TableDefs.Append tdf
CurrentDb.Execute "CREATE UNIQUE INDEX PK_dbo_vwFeedback_PrimaryKey ON dbo_vwFeedback (DataSetID, FeedbackRef) WITH PRIMARY"

NOTE: The above is for a SQL Server VIEW, it is identical for a SQL Server TABLE, but you do not need the CurrentDB.Execute line (if your primary key is correctly set up on the Server).

The code is in the place of linking a table and specifying a primary key manually.

If you do not specifying the creation of an index for SQL Server VIEWs manually or with the above method, you will only get a READ ONLY view and you may experience erroneous data returned, see comments below for examples.


回答1:


After linking the table with the code from your question, you need to do this:

CurrentDb.Execute "CREATE UNIQUE INDEX SomeIndex ON SomeTable (PrimaryKeyColumn) WITH PRIMARY"

See VBA Code to Add Linked Table with Primary Key for a complete example.

Note that you do not need to do this if you link a table - Access will detect the primary key automatically (as Remou made clear in his comment below).

But when you link a SQL Server view in Access, it is very important to specify a proper primary key for the view in Access.
If you specify the wrong key (= you select columns that don't identify a unique record) or no key at all, Access will link the view as read-only table (as you already noticed).

Plus, it will screw up the displayed rows - see Why does linked view give different results from MS Access vs SQL Manager? for more explanation.
(read my answer, and my comments under the other answer)



来源:https://stackoverflow.com/questions/11526435/how-to-specify-primary-key-when-using-vba-to-create-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!