要将自动编号字段添加到现有表格,只需在设计视图中打开表格,输入Field Name
并从下拉列表中选择“自动编号” Data Type
:
Access 将使用表中任何现有记录的自动编号值填充新字段。
编辑重新:影响将自动编号值应用于现有记录的顺序
与许多其他数据库操作一样,在将自动编号值分配给现有记录时,基本上不能保证Access 将使用任何特定顺序。但是,如果我们看几个示例,我们可以看到 Access可能会如何做到这一点。
请考虑以下名为 [Events] 的示例表。这些行是按随机顺序输入的,并且没有主键:
EventDate Event
---------- --------------
2012-06-01 it's June
2012-10-01 it's October
2012-09-01 it's September
2012-12-01 it's December
2012-11-01 it's November
2012-07-01 it's July
2012-04-01 it's April
2012-08-01 it's August
2012-02-01 it's February
2012-01-01 it's January
2012-03-01 it's March
2012-05-01 it's May
现在我们将使用上述过程简单地添加一个名为 [ID] 的自动编号字段。完成之后
SELECT * FROM Events ORDER BY ID
返回
EventDate Event ID
---------- -------------- --
2012-06-01 it's June 1
2012-10-01 it's October 2
2012-09-01 it's September 3
2012-12-01 it's December 4
2012-11-01 it's November 5
2012-07-01 it's July 6
2012-04-01 it's April 7
2012-08-01 it's August 8
2012-02-01 it's February 9
2012-01-01 it's January 10
2012-03-01 it's March 11
2012-05-01 it's May 12
现在让我们回到表的旧副本,看看是否存在主键会产生影响。我们将 [Event Date] 设为主键,将更改保存到 table,然后添加 [ID] AutoNumber 字段。完成之后,上面的select语句给了我们
EventDate Event ID
---------- -------------- --
2012-06-01 it's June 1
2012-10-01 it's October 2
2012-09-01 it's September 3
2012-12-01 it's December 4
2012-11-01 it's November 5
2012-07-01 it's July 6
2012-04-01 it's April 7
2012-08-01 it's August 8
2012-02-01 it's February 9
2012-01-01 it's January 10
2012-03-01 it's March 11
2012-05-01 it's May 12
嗯,一样的。因此,即使存在主键,看起来自动编号值也会以自然顺序(将记录添加到表中的顺序)分配给表。
好的,如果是这种情况,那么让我们使用生成表查询以不同的顺序创建表的新副本
SELECT Events.EventDate, Events.Event
INTO Events2
FROM Events
ORDER BY Events.EventDate;
现在让我们将 [ID] AutoNumber 字段添加到该新表中,看看我们得到了什么:
SELECT * FROM Events2 ORDER BY ID
返回
EventDate Event ID
---------- -------------- --
2012-01-01 it's January 1
2012-02-01 it's February 2
2012-03-01 it's March 3
2012-04-01 it's April 4
2012-05-01 it's May 5
2012-06-01 it's June 6
2012-07-01 it's July 7
2012-08-01 it's August 8
2012-09-01 it's September 9
2012-10-01 it's October 10
2012-11-01 it's November 11
2012-12-01 it's December 12
如果这是我们想要的顺序,那么我们可以删除 [Events] 表并将 [Events2] 重命名为 [Events]。