DELETE查询后更新自动编号字段

时间:2014-04-11 23:21:18

标签: c++ sql ms-access-2007 ado

引言及相关资料:

我有 MS ACCESS 2007 数据库,我使用 ADO C ++ 进行编辑。

问题:

我的问题是主键也代表记录的序数,删除后应该正确更新。主键是自动编号类型

以下是我所说的一个例子:

| #PK | Other data ... |
|  1  |      ...       |
|  2  |      ...       |
|  3  |      ...       |
|  4  |      ...       |
|  5  |      ...       |

现在,如果删除第3条记录,我会遇到以下问题:

| #PK | Other data ... |
|  1  |      ...       |
|  2  |      ...       |
|  4  |      ...       |
|  5  |      ...       |

但我应该得到以下结果:

| #PK | Other data ... |
|  1  |      ...       |
|  2  |      ...       |
|  3  |      ...       | // edited to reflect the change ( previous value was 4 )
|  4  |      ...       | // edited to reflect the change ( previous value was 5 )

如果我删除最后一条记录然后插入新记录,我会得到这样的结果:

| #PK | Other data ... |
|  1  |      ...       |
|  2  |      ...       |
|  3  |      ...       |  
|  4  |      ...       | 
|  6  |      ...       |  // this should be 5

问题:

执行DELETE query后,有没有办法以编程方式更新自动编号字段

编辑:

因为我知道这是一个不好的做法,我宁愿添加应该是序号的新字段,所以我的表格看起来像这样:

| #PK | Ordinal | Other data ... |
|  1  |    1    |      ...       |
|  2  |    2    |      ...       |
|  4  |    3    |      ...       |  
|  5  |    4    |      ...       | 

但我希望它能自动更新。如果无法做到这一点,我希望在执行删除后使用SQL query更新字段。

谢谢。

最好的问候。

3 个答案:

答案 0 :(得分:3)

这是可能的,但不是正确的方法。主键用于关系,因此如果更改值,则需要更新所有相关表。即使您目前没有任何相关的表格,您仍然应该考虑为订单添加单独的字段,否则将来当您想要添加相关表格时可能会面临同样的问题。

编辑要回答您的问题:

有没有办法添加另一个代表序号的字段,并会在插入新记录后自动增加?

如果将其设置为自动编号,它将自动递增,但您将无法修改它。您可以将其设置为数字,当您插入时,可以使用SELECT MAX(oredinal) + 1 FROM mytable来增加它。

答案 1 :(得分:1)

对于MS Access,请使用

ALter Table Customer alter column CustomerID Counter(1,1)

对于Sql Server

DBCC CHECKIDENT (orders, RESEED, 0)

这会将下一个ID的值设置为1,您可以使用上面的命令。

参考网址@ http://www.howtogeek.com/howto/database/reset-identity-column-value-in-sql-server/

答案 2 :(得分:0)

我决定在我的表格中添加一个新字段,该字段将保存记录的序号。

如果我们假设该字段名为 OrdinalNumber ,则以下解决方案适用于我:

// when inserting record, I just had to add COUNT( PK ) + 1
INSERT INTO MyTable (  OrdinalNumber , ... ) SELECT COUNT( PK ) + 1 , ...  
    from  MyTable ;

// when deleting, I had to perform following two queries :
DELETE from MyTable where PK = ? ;

// decrement all the successors ordinal number by one
UPDATE MyTable set OrdinalNumber = (  OrdinalNumber - 1 ) where ( PK > ?  );

一切似乎都运作良好。我希望有一个更简单的方法......

感谢大家的帮助。我已经提出了所有答案。

相关问题