Retrieve inserted row ID in SQL

前端 未结 4 1230
感情败类
感情败类 2020-12-06 02:11

How do I retrieve the ID of an inserted row in SQL?

Users Table:

Column  | Type
--------|--------------------------------
ID      | * Auto-incremen         


        
4条回答
  •  孤城傲影
    2020-12-06 03:03

    In SQL Server, you can do (in addition to the other solutions already present):

    INSERT INTO dbo.Users(Name, Age) 
    OUTPUT INSERTED.ID AS 'New User ID'
    VALUES('charuka', 12)
    

    The OUTPUT clause is very handy when doing inserts, updates, deletes, and you can return any of the columns - not just the auto-incremented ID column.

    Read more about the OUTPUT clause in the SQL Server Books Online.

提交回复
热议问题