SQL Server - Return value after INSERT

2019-01-01 12:33发布

I'm trying to get a the key-value back after an INSERT-statement. Example: I've got a table with the attributes name and id. id is a generated value.

    INSERT INTO table (name) VALUES('bob');

Now I want to get the id back in the same step. How is this done?

We're using Microsoft SQL Server 2008.

11条回答
大哥的爱人
2楼-- · 2019-01-01 12:44

This is how I use OUTPUT INSERTED, when inserting to a table that uses ID as identity column in SQL Server:

'myConn is the ADO connection, RS a recordset and ID an integer
Set RS=myConn.Execute("INSERT INTO M2_VOTELIST(PRODUCER_ID,TITLE,TIMEU) OUTPUT INSERTED.ID VALUES ('Gator','Test',GETDATE())")
ID=RS(0)
查看更多
爱死公子算了
3楼-- · 2019-01-01 12:52

the best and most sure solution is using SCOPE_IDENTITY. just you have to get the scope identity after every insert and save it in a variable because you can call two insert in the same scope. @identity and @@identity may be they work but they are not safe scope. you can have issues in a big application

  declare @duplicataId int
  select @duplicataId =   (SELECT SCOPE_IDENTITY())

More detail is here Microsoft docs

查看更多
墨雨无痕
4楼-- · 2019-01-01 12:54

You can append a select statement to your insert statement. Integer myInt = Insert into table1 (FName) values('Fred'); Select Scope_Identity(); This will return a value of the identity when executed scaler.

查看更多
何处买醉
5楼-- · 2019-01-01 12:56

@@IDENTITY Is a system function that returns the last-inserted identity value.

查看更多
刘海飞了
6楼-- · 2019-01-01 12:56

* Parameter order in the connection string is sometimes important. * The Provider parameter's location can break the recordset cursor after adding a row. We saw this behavior with the SQLOLEDB provider.

After a row is added, the row fields are not available, UNLESS the Provider is specified as the first parameter in the connection string. When the provider is anywhere in the connection string except as the first parameter, the newly inserted row fields are not available. When we moved the the Provider to the first parameter, the row fields magically appeared.

查看更多
萌妹纸的霸气范
7楼-- · 2019-01-01 13:01

No need for a separate SELECT...

INSERT INTO table (name)
OUTPUT Inserted.ID
VALUES('bob');

This works for non-IDENTITY columns (such as GUIDs) too

查看更多
登录 后发表回答