我正在尝试有选择地将数据从 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 中字段的类型?
你有什么线索吗?
此致
