Thursday, April 7, 2011

How to get Insert id in MSSQL in PHP?

What the question title says. With a query such as SELECT @@IDENTITY AS ins_id, do I need to supply the table name or any other info to specify which table/database i'm talking about?

From stackoverflow
  • No; it works much like SELECT LAST_INSERT_ID() in mysql, retrieving the last identity value inserted. You may want to take a look at this in-depth examination for more on what you might want to be concerned about with it.

  • @@IDENTITY returns the most recent identity generated in the current session. In most cases you'll probably want to use SCOPE_IDENTITY instead, which returns the most recent identity generated in the current scope.

    For example, if you insert a row into table1, but that insert fires a trigger which inserts a row into table2, then @@IDENTITY will return the identity from table2 whereas SCOPE_IDENTITY will return the identity from table1.

    INSERT INTO my_table (my_column) VALUES ('test')
    
    -- return the most recent identity from my_table
    -- regardless of any other inserts done by triggers etc
    SELECT SCOPE_IDENTITY() AS ins_id
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.