How to set primary key when linking with CreateTableDef

别等时光非礼了梦想. 提交于 2019-11-27 08:01:07

问题


In a MS Access database, I'm connecting to views in a SQL Server database like this:

Dim s  As String
s = "ODBC;DSN=mydb;Trusted_Connection=Yes;DATABASE=mydb;"

Dim td As TableDef
Set td = CurrentDb.CreateTableDef("vwMyView", 0, "MySchema.vwMyView", s)

CurrentDb.TableDefs.Append td
CurrentDb.TableDefs.Refresh

This creates a linked table, which is linked to a view in SQL Server.

However, I cannot insert/update/delete, because Access does not know the "primary key". How can the information about the primary key added in VBA ?

When using the Linked Table Wizard, you are always asked to select the unique key columns from a listbox. I want to reproduce this behaviour in VBA.


回答1:


You can always update the table you just attached to include an Index/Primary key. Something like,

Dim s  As String
s = "ODBC;DSN=mydb;Trusted_Connection=Yes;DATABASE=mydb;"

Dim td As TableDef
Set td = CurrentDb.CreateTableDef("vwMyView", 0, "MySchema.vwMyView", s)

CurrentDb.TableDefs.Append td

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

CurrentDb.TableDefs.Refresh

Set td = Nothing

Not sure if you need to refresh the CurrentDB before creating an INDEX. Try refreshing without first, if it does not work - refresh it then Execute the CREATE statement.




回答2:


CREATE INDEX <YourIndexName> ON <YourTableName>(<YourFieldName>) WITH PRIMARY


来源:https://stackoverflow.com/questions/30915181/how-to-set-primary-key-when-linking-with-createtabledef

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