在一个存储过程中实现:获取刚插入数据库后返回的id,并将其赋值给变量比如:declare @temp intinsert into table(name) 
output inserted.id
 values(@name)如何将id赋值给@temp呢

解决方案 »

  1.   

    declare @temp int
    insert into table(name)  
    set  @temp =@@IDENTITY
    --=@@IDENTITY 返回最后插入的标识值
      

  2.   

    IF OBJECT_ID('tempdb..#temp', 'u') IS NOT NULL
    DROP TABLE #temp
    GO
    CREATE TABLE #temp
    (
    id INT, --#1.如果不是自增列
    [name] NVARCHAR(10)
    )
    GO
    --SQL:
    DECLARE @table TABLE(id int)
    declare @temp INTinsert into #temp(id, name) 
    OUTPUT inserted.id
    INTO @table
    values(2, 'test')--#2.如果是自增列
    SET @temp = SCOPE_IDENTITY()SELECT * FROM @table
    --RESULT:
    /*
    id
    2
    */
      

  3.   

    CREATE PROC TEST
    ASdeclare @temp intinsert into table(name)  SELECT @temp  = @@IDENTITYRETURN @temp  
      

  4.   


    declare @temp int
    insert into table(name)  
    set  @temp =@@IDENTITY
      

  5.   

    @@IDENTITY
    SCOPE_IDENTITY()去查查这两个的用法