get new SQL record ID

前端 未结 8 2035
南方客
南方客 2020-12-17 19:31

How can I get back the autogenerated ID for a new record I just inserted? (Using ASP classic and MSSQL 2005)

相关标签:
8条回答
  • 2020-12-17 20:12
    SELECT SCOPE_IDENTITY() 
    

    using @@IDENTITY can have unexpected results, so be careful how you use that one. Triggers that insert records to other tables will cause the @@IDENTITY value to change - where SCOPE_IDENTITY() will give you the last identity from only your current scope.

    Here's a sample that'll show the difference between @@IDENTITY and SCOPE_INSERT() and how they can return different values..

    use tempdb
    go
    create table table1
        (ID int identity)
    go
    create table table2
        (ID int identity(100, 1))
    go
    create trigger temptrig 
        on table1 
        for insert
    as
    begin
    
        insert  table2 
         default values;
    
    end
    go
    insert  table1 
    default values;
    select  SCOPE_IDENTITY(), 
            @@IDENTITY
    

    Another option that nobody has discussed here is to use the OUTPUT clause that is in SQL 2005. In this case, you'd just have to add the output clause to your insert, and then catch that recordset from your code. This works well when inserting multiple records instead of just 1...

    use tempdb
    go
    create table table1
        (ID int identity)
    go
    insert   table1 
    output   inserted.ID
    default values;
    --OR...
    insert   table1 
    output   inserted.$identity
    default values;
    
    0 讨论(0)
  • 2020-12-17 20:14

    Where multiple records need to inserted at once in a set-based fashion, it can get more interesting.

    I have sometimes used GUIDs generated clientside (but for classic ASP you'd probably need to use a utility to generate the values) or, more often, a NEWSQUENTIALID() constraint on the GUID key column at the server end.

    I'm aware not everyone like GIUDS though, for some quite valid reasons (their size and how it affects indexing/paging for one).

    http://www.sqlmag.com/Articles/Index.cfm?ArticleID=50164&pg=2

    0 讨论(0)
提交回复
热议问题