这并不是因为它没有 DSN,而是因为您是通过 VBA 创建的。如果您通过 Access GUI 链接视图,它会要求您提供主键。
但通过 VBA,它不知道主键,因此链接视图不可更新。对于表,Access 通过 ODBC 自动获取主键,因此表可以工作。
解决方案:通过 VBA 链接视图后设置主键:
S = "CREATE INDEX PrimaryKey ON MyViewName (MyPrimaryKeyField) WITH PRIMARY"
DB.Execute S
如果您有很多视图,并定期重新链接它们(例如从开发数据库到生产数据库),那么对它们的名称和 PK 进行硬编码就变得不切实际。我编写了一个函数来从链接视图中检索所有主键索引,并在链接后重新创建它们。
如果你愿意,我可以挖出来。
Edit:
这就是我所做的:
' This function returns the full DSN-less connect string
Private Function ODBC_String() As String
' In the real world there are several constants and variable in there
ODBC_String = "ODBC;DRIVER={SQL Server};SERVER=aaa;DATABASE=bbb;UID=ccc;PWD=ccc;LANGUAGE=us_english;TRUSTED_CONNECTION=No"
End Function
链接表或视图第一次,我使用这个(strTable是表/视图名称):
DoCmd.TransferDatabase acLink, "ODBC", ODBC_String(), acTable, strTable, strTable, False, True
对于表,主键 (PK) 是自动确定的。对于视图,我使用“访问”对话框窗口来指定 PK,就像我手动链接视图一样。
PK 信息存储在链接视图的 TableDef 对象中,因此我不必在任何地方对其进行硬编码。
为了存储所有链接视图的 PK 信息,我有这个表(为了简单起见,它是 Access 前端中的本地表):
t_LinkedViewPK
ViewName Text(100)
IndexFields Text(255)
和这个功能。所有视图(和only视图)称为“v_*”,因此我可以按名称列出它们。
我实际上不确定您是否可以从 TableDef 对象确定它是否指向表或视图。
Private Sub StoreViewPKs()
Dim TD As TableDef
Dim idx As index
Dim FD As Field
Dim RS As Recordset
Dim S As String
' DB is a global Database object, set to CurrentDB
DB.Execute "Delete * From t_LinkedViewPK"
Set RS = DB.OpenRecordset("t_LinkedViewPK")
For Each TD In DB.TableDefs
If TD.Name Like "v_*" Then
' Views must have exactly one index. If not: panic!
If TD.Indexes.Count <> 1 Then
MsgBox "View " & TD.Name & " has " & TD.Indexes.Count & " Indizes.", vbCritical
Stop
End If
Set idx = TD.Indexes(0)
' Build field list (the index may contain multiple fields)
S = ""
For Each FD In idx.Fields
If S <> "" Then S = S & ", "
S = S & FD.Name
Next FD
RS.AddNew
RS!ViewName = TD.Name
RS!IndexFields = S
RS.Update
End If
Next TD
RS.Close
End Sub
当我更改表或视图结构,或更改源数据库时(这是通过更改输出来完成的)ODBC_String()
),我称这个函数为:
Public Function Sql_RefreshTables()
Dim TD As TableDef
Dim S As String
Dim IdxFlds As String
DB.TableDefs.Refresh
' save current Indizes for Views (recreated after .RefreshLink)
Call StoreViewPKs
For Each TD In DB.TableDefs
If Len(TD.Connect) > 0 Then
If Left(TD.Connect, 5) = "ODBC;" Then
Debug.Print "Updating " & TD.Name
TD.Connect = ODBC_String()
TD.RefreshLink
' View?
If TD.Name Like "v_*" Then
IdxFlds = Nz(DLookup("IndexFields", "t_LinkedViewPK", "ViewName = '" & TD.Name & "'"))
If IdxFlds = "" Then Stop
' Create PK
S = "CREATE INDEX PrimaryKey ON " & TD.Name & " (" & IdxFlds & ") WITH PRIMARY"
DB.Execute S
End If
End If
End If
Next TD
DB.TableDefs.Refresh
End Function
Note:
代替桌子t_LinkedViewPK
,可以使用字典对象。但是在开发这个的过程中,将它作为一个实际的表格非常有用。