我在数据库中添加了一条记录,其中有一个字段是标识字段,自动生成递增值,我应该如何在添加完记录后取得它的值?表中有三个字段:
字段1 autonumber --索引字段
字段2
字段3insert into ly(字段2,字段3) values('值1','值2')
那么在添加完这条记录后,我需要将字段1的值添加到另一个表中,我要如何做?

解决方案 »

  1.   

    在你INSERT完之后,
    写我上面那一句
      

  2.   

    使用存储过程,如下:
    下面的示例向带有标识列的表中插入一行,并用 @@IDENTITY 显示在新行中使用的标识值。INSERT INTO jobs (job_desc,min_lvl,max_lvl)
    VALUES ('Accountant',12,125)
    SELECT @@IDENTITY AS 'Identity'
      

  3.   

    怪我没讲清楚:
    SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
    GO
    SELECT   @@IDENTITY AS [@@IDENTITY]
    GO--Here is the result set.
    SCOPE_IDENTITY
    4
    /*SCOPE_IDENTITY returned the last identity value in the same scope, which was the insert on table TZ*/@@IDENTITY
    115
    /*@@IDENTITY returned the last identity value inserted to TY by the trigger, which fired due to an earlier insert on TZ*/
    @@identity是最后添加的记录的值,如果在insert语句后,别人同时也执行了insert语句,那不是得不到正确的@@identity ,那SCOPE_IDENTITY()是否可以呢,
    因为在sql的帮助中讲到:SCOPE_IDENTITY 只在当前作用域内返回值,而 @@IDENTITY 不限于特定的作用域。如果是在一个事务过程中完成,是否就可以用@@identity呢?
    如果可以,是否有事务处理的代码,想看一看.