SQL statement returns primary key scope_identity ()

Source: Internet
Author: User

After the SQL statement is used
Scope_identity ()

Of course you can also use SELECT @ @IDENTITY

But using the SELECT @ @IDENTITY is the go-to-global update. It is possible to obtain an incorrect value.

Example:
INSERT INTO dbo. Sns_blogdata (UserName) VALUES (' Santai ');
SELECT scope_identity ()

Gets the primary key return value for the insert into operation of the Sql-server database, scope_identity

After inserting a record, you want to get the return value of the primary key in its data table immediately. This primary key is generated automatically, in fact, there are many ways to implement, such as a query again, get out. Or to take the maximum value before inserting the data, add one to the maximum, and so on, many ways, but some are inconvenient.
The quickest way to feel personal is to get the value of the primary key directly after inserting the data, and then return.
Here's how:
The SQL statements are as follows:
INSERT into TableName (fieldname ...) VALUES (value ...) SELECT @ @IDENTITY as Returnname;
Add the SELECT @ @IDENTITY as returnname in the SQL statement; The value used to get the primary key.

SQL statement returns primary key scope_identity ()

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.