How to get the primary key ID of the newly inserted data of the database accurately and efficiently

Source: Internet
Author: User

For example, we have created a new table userinformation, fields as follows ID, primary key, self-increment, other fields name,pwd,Email

Then we'll perform a new insert operation:

INSERT INTO UserInformation
(name,pwd,email) VALUES (' xiaoming ', ' 123 ', ' 111 ')

We want to get the value of the primary key to insert this data when inserting data.

There are two ways to resolve this:

1, one is to enter a field directly, and then query, the code is as follows:

INSERT INTO UserInformation
(name,pwd,email) VALUES (' Xiao Zhang ', ' 123 ', ' 111 ')
SELECT @ @identity

After insertion, but this is not completely accurate.

Insert Into[test1]. [dbo]. [UserInformation]
(name,pwd,email) VALUES (' Xiao Zhang ', ' 123 ', ' 111 ')
SELECT @ @identity

A database lock is involved, and if a database lock is adjusted, there may be errors when there is a large amount of data in parallel when the number level is particularly large.

2, the other method is the output at the same time as the insertion, the code is as follows:

INSERT INTO UserInformation
(name,pwd,email) output inserted. Id values (' xiaoming ', ' 123 ', ' 111 ')

In addition to the primary key, you can also output other fields, accurate and efficient.

It is recommended to use the second

  Insert  into [Db_date_plan].[dbo].[T_userinfo](username,userpassword,useremail) output inserted. Id,inserted.usernameValues('Xiao Ming','12322','11122')Update [Db_date_plan].[dbo].[T_userinfo] SetUserName='XXX'OUTPUT inserted.idWHEREUserPassword='Admin'

Excerpt from: https://www.cnblogs.com/zhangchengye/p/5148545.html

How to get the primary key ID of the newly inserted data of the database accurately and efficiently

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.