0

我正在尝试有选择地将数据从 SQL Server 表导入 MS Access 表。

据我了解,使用 DoCmd 命令可以很容易地导入完整表。

不幸的是,我需要的数据存储在大表中,我只需要其中的一部分。

到目前为止,我能够导入数据并将它们存储在记录集中。现在我想创建一个表来存储在 MS Access 中,但 VBA 抱怨类型不匹配(运行时错误 3421)。

到目前为止,我的代码是这样的——第一部分:连接到 SQL Server 数据库和数据采集

Sub Test()

Dim Table As String, SQL As String, SQLTable As String
Dim server As String, Database As String, GetClientDB As String

'CaseID = 0
'SolutionID = 498232069
Table = "PrSale"
SQL = PrSale(SolutionID, CaseId)
SQLTable = TableSQL(Table, SolutionID, CaseId)

server = ServerID
Database = DatabaseID
GetClientDB = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=" + Database + ";Data Source=" + server

Set DBConnection = New ADODB.Connection
DBConnection.CursorLocation = adUseServer

DBConnection.ConnectionString = GetClientDB
DBConnection.Open

Dim myview As ADODB.Recordset

'myview.Open SQLTable, DBConnection, adOpenStatic
Set myview = DBConnection.Execute(SQLTable)

第二部分 - 表创建和字段定义:

Call DeleteIfExists(Table)

'Cria a tabela na base de dados
Dim tdf As DAO.TableDef
Set tdf = CurrentDb.CreateTableDef(Table)

'Lê os campos da tabela original e replica na tabela local
For Each viewfld In myview.Fields
    Dim fld As DAO.Field
    Dim mytype As Integer
    
    Select Case viewfld.Type
        Case 200   'VarChar
        mytype = dbText

        Case 3 'integer
        mytype = dbInteger

        Case 202 'VarWChar
        mytype = dbText

        Case 5 'Double
        mytype = dbDouble

        Case 2 'smallint
        mytype = dbInteger

        Case Else
        mytype = dbText
    End Select
    If Table = "PMPERIOD" Then
        If viewfld.Name = "StartDate" Or viewfld.Name = "StopDate" Then
            mytype = dbDate
        End If
    End If
    If Table = "PMSELL" Then
        If viewfld.Name = "GRPNUM" Then
        mytype = dbText
        End If
    End If
    Set fld = tdf.CreateField(viewfld.Name, mytype)
    tdf.Fields.Append fld
Next

CurrentDb.TableDefs.Append tdf

第三部分 - 使用存储在 myview 记录集中的数据完成表:

If myview.EOF Then
    GoTo Skip_
Else
End If

myview.MoveFirst

Do While Not myview.EOF
    'Preenche as tabelas com os dados do Recordset
    Dim myrecordset As DAO.Recordset
    Set myrecordset = CurrentDb.OpenRecordset(Table)
    myrecordset.AddNew
    For Each viewfld In myview.Fields
        myrecordset.Fields(viewfld.Name).Value = viewfld.Value
        Dim j As Integer
        j = 10
    Next
    myrecordset.Update
    myview.MoveNext
Loop

Skip_:

End Sub

就我能够调试而言,直到第二部分似乎是正确的,尽管我无法验证字段类型。该表是在具有正确标签的 MS Access 数据库中创建的,但它会因错误 3421 而崩溃!:(

如何验证 tdf 中字段的类型?

你有什么线索吗?

此致

4

1 回答 1

2

只需设置一个指向 sql server 表的表链接。

然后启动 Access 查询生成器。

现在创建一个空白的新查询,将链接表放入 sql server。

现在在功能区中,将查询更改为生成表查询。

你有这个:

在此处输入图像描述

因此,您可以选择字段名称、设置标准,当您运行该查询时,它将创建一个本地表。

所以,你不需要代码来过滤

您不需要代码来选择某些列

您不需要代码来重命名目标表中的列名。

只需将链接表设置到 sql server 即可。

然后将该链接表放入查询生成器中。

在功能区上,选择“制作表”

此时,您可以选择部分或所有列。

此时,您可以为某些列输入标准以限制数据。

运行查询 - 你完成了。无需编写代码,甚至无需在此处弄乱连接字符串。

于 2021-10-05T16:58:58.297 回答