This article is a mirror article of machine translation, please click here to jump to the original article.

View: 11401|Reply: 0

[Source] MSSQL gets the id of the currently inserted data

[Copy link]
Posted on 4/30/2015 10:29:50 AM | | |

For example, we create a new table T_User with the following fields u_id, primary key, identifier, user_name......

  Then let's perform a new insert operation:

     insert into T_User(user_name,user_password,user_email,user_ip)
values('admin','123456','32962435@qq.com','58.20.158.20')   ;

     One day, we want to get the value of the u_id that is inserted when adding new inserted data, and we know that from MSSQL2005 onwards, we can add an output to enter a certain value, and we can use it to achieve it

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

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, not at the end of the sql statement, otherwise it will be wrong, inserted is fixed, If you want to enter a field that is currently inserted, just follow this field, what we want to get is u_id so inserted.u_id
values('admin','123456','32962435@qq.com','58.20.158.20')   ;

   Another way is to use @@identity, @@identity is a global variable built into the system, which is to enter the last identifier, which we can do in two steps or in one step

The code for the one-step implementation is as follows

   insert into T_User(user_name,user_password,user_email,user_ip)  output @@identity
values('admin','123456','32962435@qq.com','58.20.158.20')   ;




Previous:The Beijing Cybersecurity Anti-Fraud Alliance released a report on online fraud crimes
Next:Let's get married!! The fire is coming!
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com