【问题标题】:Import data according to table relationship order按表关系顺序导入数据
【发布时间】:2009-05-13 07:11:24
【问题描述】:

我正在尝试在 access 数据库中创建一个通用的导入 VBA 函数。 (我会链接一个类似数据库的外部表,然后将它们的数据导入本地表。)

对于初学者,该函数应该获取本地数据库中的表列表,按主键/外键排序,以便根据表关系规则进行导入。

因此,我正在尝试做类似以下的事情: http://education.sqlfarms.com/education/ShowPost.aspx?PostID=50 ,但在访问 VBA。

因此,我需要帮助获取本地表的列表,以允许插入的方式排序(具有主键的表在关系中具有相应外键的表之前列出)

请帮忙

【问题讨论】:

  • 请确定您需要帮助的部分。

标签: ms-access import


【解决方案1】:

这里有一个粗略的大纲,可能会有所帮助。

Option Explicit

Public i

Sub GetTableOrder()
Dim tdf As TableDef
Dim db As Database
Dim rs As New ADODB.Recordset

Set db = CurrentDb

''Create a disconnected recordset
rs.Fields.Append "TableName", adVarChar, 50
rs.Fields.Append "Level", adInteger

rs.CursorType = adOpenStatic
rs.Open

For Each tdf In db.TableDefs
    ''Skip system tables
    If Left(tdf.Name, 4) <> "Msys" Then
        rs.AddNew "TableName", tdf.Name
        rs.Update

        i = 0
        RelRun tdf.Name, i

        rs!Level = i
        rs.Update
    End If
Next

rs.MoveFirst

''Delete order
''ASC is the default sort order, so it is not
''necessary, and only included for illustration.

rs.Sort = "Level ASC"

''Not a good place for this line
''It is only here for convenience (mine :) )
DelRecs rs

End Sub

Function RelRun(TableName, i)
Dim rel As Relation
Dim db As Database
Dim blnFound As Boolean
Dim TableForeign As String

Set db = CurrentDb

    For Each rel In db.Relations

        If rel.Table = TableName Then
            i = i + 1
            TableForeign = rel.ForeignTable
            blnFound = True
        End If

    Next

    If blnFound Then
        ''Round and round to the end of the line
        RelRun TableForeign, i
    End If

End Function

Sub DelRecs(rs As ADODB.Recordset)
Dim strSQL As String
Dim db As Database

Set db = CurrentDb

    Do While Not rs.EOF
        strSQL = "DELETE FROM [" & rs!TableName & "]"
        db.Execute strSQL
        Debug.Print rs!TableName & " : " & db.RecordsAffected
        rs.MoveNext
    Loop

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-11
    • 2018-07-04
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    相关资源
    最近更新 更多