MSSQL obtains the id of the inserted data

Source: Internet
Author: User

For example, we have created a new table T_User with the following u_id field, primary key, as the identifier, user_name ......

Then we will execute a new insert operation:

Insert into T_User (user_name, user_password, user_email, user_ip)
Values ('admin', '000000', '1970 @ qq.com ', '58. 0000158.20 ');

One day, we want to get the u_id value of the inserted data when adding the inserted data. We know that an output is added after MSSQL2005 to enter a value, we can use it to implement

There are two methods. One is to directly enter a field, such:

Insert into T_User (user_name, user_password, user_email, user_ip) output inserted. u_id // output inserted. u_id must be placed before values, and cannot be placed at the end of the SQL statement. Otherwise, errors occur and inserted is fixed, if you want to enter a field that is currently inserted, this field will be followed. We want to obtain u_id, so it is inserted. u_id
Values ('admin', '000000', '1970 @ qq.com ', '58. 0000158.20 ');

Another method is to use @ identity, and @ identity is a built-in global variable, which is the last identifier of the input, we can do this either in two steps or in one step.

The code for one-step implementation is as follows:

Insert into T_User (user_name, user_password, user_email, user_ip) output @ identity
Values ('admin', '000000', '1970 @ qq.com ', '58. 0000158.20 ');

Related Article

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.