简体   繁体   English

如何将 SQL Server 表中的数据追加到 Access 表?

[英]How to append data from a SQL Server table to an Access table?

I am trying to write a query in MS access to open a connection to a local SQL Server and then to import select tables into MS Access.我正在尝试在 MS Access 中编写查询以打开与本地 SQL Server 的连接,然后将选择表导入 MS Access。

My code runs until the Cn.Execute statement.我的代码一直运行到Cn.Execute语句。 I get我得到

Run-time error '-2471765 (80040e37)' [Microsoft][ODBC SQL Server Driver][SQL Server] Invalid Object Name 'dbo_SQLServertable'.运行时错误“-2471765 (80040e37)”[Microsoft][ODBC SQL Server 驱动程序][SQL Server] 无效的对象名称“dbo_SQLServertable”。

I need to import additional tables so I need a code that will work when I change table names.我需要导入额外的表,所以我需要一个代码,当我更改表名时,它会起作用。

Private Sub Command28_Click()    
        
    Dim Cn As ADODB.Connection
    Dim Server_Name As String
    im Database_Name As String
    Dim User_ID As String
    Dim Password As String
    Dim SQLStr As String
    Dim rs As ADODB.Recordset
    Set rs = New ADODB.Recordset
    
    Server_Name = "" ' Enter your server name here
    Database_Name = "Test" ' Enter your database name here
    User_ID = "" ' enter your user ID here
    Password = "" ' Enter your password here
       
    Set Cn = New ADODB.Connection
    Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & ";"
    
    Cn.Execute "INSERT INTO Access Table SELECT dbo_SQLServerTable.* FROM dbo_SQLServerTable;"
    
    Set rs = Nothing
    Cn.Close
    Set Cn = Nothing

I made changes and I get a new error message我进行了更改,但收到一条新的错误消息

Run-time error '-2147216900 (80040e14)' [Microsoft][ODBC SQL Server Driver][SQL Server] Cannot Insert the value NULL into column 'DiagnosisOrdinal', table 'Office.dbo.Test' column does not allow nulls.运行时错误 '-2147216900 (80040e14)' [Microsoft][ODBC SQL Server 驱动程序][SQL Server] 无法将值 NULL 插入列 'DiagnosisOrdinal',表 'Office.dbo.Test' 列不允许空值。 Insert fails.插入失败。

It appears that my insert statement is still referencing (or trying to reference) a table in the SQL server.看来我的插入语句仍在引用(或试图引用)SQL 服务器中的表。 'Office' is the database name that I am pulling from. “Office”是我从中提取的数据库名称。

Do I have to close the connection and then paste the data into my local Access table?我是否必须关闭连接然后将数据粘贴到我的本地 Access 表中? Will I then have to re-open and close the connection if I want to do this for multiple tables?如果我想对多个表执行此操作,是否必须重新打开和关闭连接?

I changed my execute statement from我改变了我的执行语句

Cn.Execute "INSERT INTO Access Table SELECT dbo_SQLServerTable.* FROM dbo_SQLServerTable;"

to

Cn.Execute "INSERT INTO Test(VisitID, Provider) SELECT VisitID, Provider FROM dbo.SQLServerTable;"

You don't want the table prefix in your SELECT from the SQL table.您不希望在 SQL 表中的 SELECT 中使用表前缀。 Just do SELECT * FROM dbo_SQLServerTable;只需执行SELECT * FROM dbo_SQLServerTable; Best practice, though, is not to use SELECT * but rather specify the columns in case the table schemas ever change.但是,最佳实践不是使用SELECT *而是指定列以防表模式发生变化。

There's a few suggestions for this particular issue针对这个特定问题有一些建议

  1. Pass thru queries传递查询
  2. Linked Tables from SQL Server.来自 SQL Server 的链接表。 Youll prolly have to set up a dsn file which isnt too terribly difficult. Youll prolly 必须设置一个 dsn 文件,这不是非常困难。
  3. Or handle it directly in SQL Server Insert into Access from SQL Server或者直接在 SQL Server Insert into Access from SQL Server 中处理
  4. ODBC connection via VBA (what youre doing and seemingly the most convoluted)通过 VBA 的 ODBC 连接(你在做什么,看起来最复杂)

All of these approaches will work fine.所有这些方法都可以正常工作。 I suggest linked tables so you dont duplicate data but thats a cinsderation fro you since I dont knwo the requirements of the project.我建议使用链接表,这样您就不会重复数据,但这对您来说是一种耻辱,因为我不知道项目的要求。

dbo_SQLServerTable is an Access table name, not SQL server table name. dbo_SQLServerTable 是 Access 表名,而不是 SQL 服务器表名。 Because you already created the linked table dbo_SQLServerTable, you can use the following VBA code.因为您已经创建了链接表 dbo_SQLServerTable,所以您可以使用以下 VBA 代码。

Currentproject.connection.execute "INSERT INTO MyAccessTable(fld1, fld2, fld3) SELECT fld1, fld2,fld3 FROM dbo_SQLServerTable"

There is no need to create connection object in VBA code.无需在 VBA 代码中创建连接对象。 Currentproject.connection is always available to be referenced. Currentproject.connection 始终可供引用。

Least amount of code I can think of is to use a pass-through query.我能想到的最少代码是使用传递查询。

Setup a PT query to the server database in question.设置对有问题的服务器数据库的 PT 查询。

Then your code to create a new table in access would look like:然后,您在 access 中创建新表的代码如下所示:

Sub TestImport()

  Dim strSQL     As String
  
  With CurrentDb.QueryDefs("qryPassR")
     .SQL = "select * from tblHotels"
  End With
  
  Dim strLocalTable  As String
  
  strLocalTable = "zoo"
  
  CurrentDb.Execute "select * into " & strLocalTable & " FROM qryPassR"
  
End Sub

The above of course assumes you setup the connection to sql server (one database) when you created the PT query.以上当然假设您在创建 PT 查询时设置了到 sql server(一个数据库)的连接。 The above approach is nice since you don't mess around with connection strings in code.上述方法很好,因为您不会在代码中处理连接字符串。

However, given that you need (want) to specify the database (and likely server), then above becomes this:但是,鉴于您需要(想要)指定数据库(和可能的服务器),那么上面变成了这样:

Sub TestImport2()

  Dim strSQL           As String
  Dim strServer        As String
  Dim strDatabase      As String
  Dim strUser          As String
  Dim strPass          As String
  
  strServer = ""
  strDatabse = ""
  strUser = ""
  strPass = ""
  
  Dim strLocalTable       As String
  Dim strServerTable      As String
  
  With CurrentDb.QueryDefs("qryPassR")
     .Connect = dbCon(strServer, strDatabase, strUser, strPass)
     .SQL = "select * from " & strServerAble
  End With
  
  CurrentDb.Execute "select * into " & strLocalTable & " FROM qryPassR"
  
End Sub

The above uses a "handy" function to create your connection string.上面使用了一个“方便”的函数来创建你的连接字符串。

That function is as follows:该函数如下:

Public Function dbCon(ServerName As String, _
                     DataBaseName As String, _
                     Optional UserID As String = "", _
                     Optional USERpw As String, _
                     Optional APP As String = "Office 2010", _
                     Optional WSID As String = "Import") As String

   ' returns a SQL server conneciton string
   
  dbCon = "ODBC;DRIVER=" & SQLDRIVER & ";" & _
          "SERVER=" & ServerName & ";" & _
          "DATABASE=" & DataBaseName & ";"
          If UserID <> "" Then
             dbCon = dbCon & "UID=" & UserID & ";" & "PWD=" & USERpw & ";"
          End If
          dbCon = dbCon & _
          "APP=" & APP & ";" & _
          "WSID=" & WSID & ";" & _
          "Network=DBMSSOCN"

End Function

Edit编辑

Poster has asked for solution to append data into a EXISTING table.海报要求解决方案将数据附加到现有表中。

In that case, simply change this:在这种情况下,只需更改以下内容:

  CurrentDb.Execute "select * into " & strLocalTable & " FROM qryPassR"

to

  CurrentDb.Execute "INSERT INTO " & strLocalTable & " SELECT * FROM qryPassR"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM