2

我尝试以编程方式将多个表从 Microsoft SQL Server 导入 Microsoft Access。

每个 SQL Server 表都有一个标识列,相应的 Access 表也有一个自动编号列。

现在我想生成 SQL 脚本以将数据从 SQL Server 复制到 Access,并使自动编号列与 SQL Server 中的值相同。

这可能吗?

从 Access 到 SQL Server 以其他方式执行此操作时,使用 SETIDENTITY_INSERT [MyTable] ON和更高版本相当容易SET IDENTITY_INSERT [MyTable] OFF

我发现 Microsoft Access 没有这样的声明。

此外,我尝试创建要导入的 Access 表,首先使用标识字段作为类型LONG,然后使用该ALTER TABLE ... ALTER COLUMN语句切换到自动编号。我这样做失败了。

所以我的问题是:有什么方法可以实现我的目标吗?

4

3 回答 3

5

如果您Insert Into在 MS Access 中使用并指定所有列名,它应该可以工作。

我刚刚创建了一个具有以下结构的表

Id (autonumber)
Firstname (text)
Secondname (text)
Lastname (text)

我运行了这个语句

docmd.RunSQL "insert into table2 (id, firstname, secondname, lastname) values (27, 'a', 'b', 'c')"

它工作并将 27 插入自动编号列

于 2010-07-30T18:35:53.730 回答
3

假设您可以在 MS Access 数据库中同时看到 SQL Server 表(链接表)和 MS Access 表,以下是无需代码即可执行此操作的过程。这些说明适用于 Access 2013,因此虽然界面元素已移动,但这应该适用于 2003、2007 等。

您要导入的 Access 表应该没有任何数据。

  1. Close all Access objects (tables, queries, reports, etc.)
  2. Click Database Tools on the ribbon.
  3. Optional: Click Compact and Repair (this sets the AutoNumber counters back to 0 on empty tables)
  4. Click Create on the menu.
  5. Click Query Design on the ribbon. (the Show Tables dialog is open)
  6. Add the SQL Server source table to the query.
  7. Close the Show Tables dialog.
  8. Click the Append Query button on the ribbon.
  9. Select the Access table into which you want to import data and click OK.
  10. In the SQL Server table, double-click any fields that you want to import, or double-click the * field if all column names match and you want to import all fields.
  11. For each field that is added to the append query below, check that all fields map to a field in the Access table. If not, in the Append To attribute of each field, select the field in Access that should receive the data from SQL Server.
  12. Click the Run button on the ribbon.

Access will tell you how many records you are about to append - you can use this information to verify that you are getting all your data.

You can save this query if you think you'll need to use it again to sync the tables.

If you want to get fancy, you could create a delete query which deletes all the records in the access table, then create a macro which runs everything in this order:

  1. Delete records
  2. Compact and Repair Database
  3. Run import from SQL Server
于 2013-10-11T13:26:45.967 回答
0

The secret is to temporarily un-assign the autonumber as the primary key. This allows Appending AutoNumber Field to your records without any trouble (just make sure you do not have any duplicates when appending, otherwise when you re-assign the primary key you will get an error).

于 2015-07-18T07:12:18.570 回答