插入一条新数据,如何返回主键值id,id是自动增长的,请帮忙!

解决方案 »

  1.   

    create table Temp(id int identity(1,1),col int)
    go
    insert into temp select 5
    insert into temp select 8
    insert into temp select 100
    go
    --在执行插入后立即调用
    select @@IDENTITY
    /*
    ---------------------------------------
    3(1 行受影响)*/
    go
    drop table temp
      

  2.   

     @@IDENTITY、SCOPE_IDENTITY 和 IDENT_CURRENT 可以去查查 都差不多
      

  3.   

    insert ........
    select @@IDENTITY
      

  4.   

    insert into....;select @@identity
      

  5.   


    select ident_current('tb')  ---返回表tb最后一个插入的identity列的值   
      
    select @@IDENTITY  ----返回最新插入的identity值   
      
    select SCOPE_IDENTITY()  ----返回最新插入的identity值   
      
    --@@identity 和 scope_identity()的区别是 @@identity 的作用域是全部的回话,不只是当前表,会返回所有域中   
      
    --刚插入的identity值,scope_identity() 只返回当前回话中新插入的identity值   
      
    select IDENT_INCR('tb')  ---返回表tb identity列的原始增量值   
      
    select IDENT_SEED('tb')  ---返回表tb identity列的原始种子值,即起始值