使用VBA创建DSNLess连接

时间:2016-08-11 12:09:10

标签: sql-server vba postgresql ms-access-2013 access

我正在使用SQL Server从Postgresql服务器数据库表创建视图。然后我使用Access VBA创建到视图的DSNLess连接,该连接按预期执行。问题是表是以只读方式链接的。我读到,为了使其“可写”,我需要定义主键,但视图不能有主键。那么我应该改变什么才能使这个链表成为可写的呢?

这是我创建视图的SQL Server语法

ALTER VIEW [dbo].[Maestro]
AS
SELECT        *
FROM            OPENQUERY(PostegresqlConnection, 
                     'SELECT
                      empid
                      ,empaddress
                      ,empphone
                      From sentry1
                      where empstatus = ''Active'' ')
GO

这是我用来链接表中的Access VBA

Option Compare Database
'//Name     :   AttachDSNLessTable
'//Purpose  :   Create a linked table to SQL Server without using a DSN
'//Parameters
'//     stLocalTableName: Name of the table that you are creating in the current database
 '//     stRemoteTableName: Name of the table that you are linking to on the SQL Server database
'//     stServer: Name of the SQL Server that you are linking to
'//     stDatabase: Name of the SQL Server database that you are linking to
'//     stUsername: Name of the SQL Server user who can connect to SQL Server, leave blank to use a Trusted Connection
'//     stPassword: SQL Server user password
Public Function AttachDSNLessTable()
On Error GoTo AttachDSNLessTable_Err
Dim td As TableDef
Dim stConnect As String

'Alter these variables to change any settings
Dim stLocalTableName As String, stRemoteTableName As String, stServer As String, stDatabase As String, stUsername As String, stPassword As String

stLocalTableName = "LinkedMaestro"
stRemoteTableName = "Maestro"
stServer = "SSMS\Server1"
stDatabase = "TestDB"
stUsername = "Blue"
stPassword = "NotRealPassword"

For Each td In CurrentDb.TableDefs
    If td.Name = stLocalTableName Then
        CurrentDb.TableDefs.Delete stLocalTableName
    End If
Next

If Len(stUsername) = 0 Then
    stConnect = "ODBC;DRIVER=SQL Server;SERVER=" & stServer & ";DATABASE=" & stDatabase & ";Trusted_Connection=Yes"
Else
    stConnect = "ODBC;DRIVER=SQL Server;SERVER=" & stServer & ";DATABASE=" & stDatabase & ";UID=" & stUsername & ";PWD=" & stPassword
End If
Set td = CurrentDb.CreateTableDef(stLocalTableName, dbAttachSavePWD, stRemoteTableName, stConnect)
CurrentDb.TableDefs.Append td
AttachDSNLessTable = True
Exit Function

AttachDSNLessTable_Err:

  AttachDSNLessTable = False
  MsgBox "AttachDSNLessTable encountered an unexpected error: " & Err.Description

End Function

在create view语法中,字段empid是postgresql表的主键。为了使该表可以通过DSNLess连接写入,我必须改变(或做)什么?

0 个答案:

没有答案