Get the primary key return value for the insert into operation on the SQL-SERVER Database

Source: Internet
Author: User
After inserting a record, you want to immediately obtain the primary key return value in the data table. This primary key is automatically generated. In fact, there are many implementation methods, such as performing another query and obtaining it. You can also extract the maximum value before inserting data and add one to the maximum value. There are many methods, but some are inconvenient.
In my opinion, the fastest way is to directly obtain the value of the primary key after inserting data, and then return it.
The method is as follows:
The SQL statement is as follows:
Insert into tablename (fieldname...) values (value...) Select @ identity as returnname;
Add select @ identity as returnname to the SQL statement to obtain the value of the primary key.
In ProgramTo obtain the return value:
Public int sqlexecutereader (string SQL)
{
Dbopen ();
Sqlcommand mycomm = new sqlcommand (SQL, connection );
Int newid = convert. toint32 (mycomm. executescalar ());
Dbclose ();
Return newid;
}
Of course, the primary key is automatically added for the int type here. The operations of dbopen (); dbclose (); are not described here.

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.