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

View: 6787|Reply: 1

[Source] SQL Server returns the primary key after insertion

[Copy link]
Posted on 7/7/2020 11:55:16 AM | | | |
Requirements: A stored procedure, we need to insert a piece of data in tables A and B, where the main foreign key relationship between table A and table B, the columns associated with table B are the primary keys of table A, we need to insert the primary key value of table A after the insertion is completed, we need to obtain the primary key value of table A, and then insert the data into table B.

After inserting a record, you want to get the return value of the primary key in its datasheet immediately. This primary key is automatically generated.

First, create a temporary table to test, the code is as follows:


@@IDENTITY

After an INSERT, SELECT IN, or bulk copy statement completes, the @@IDENTITY contains the last identification value produced by this statement. If this statement does not affect any tables with identified columns, @@IDENTITY returns NULL. If multiple rows are inserted, multiple identifier values are generated, @@IDENTITY the last identifier value is returned. If this statement triggers one or more triggers that perform an insert operation that produces an identified value, calling @@IDENTITY immediately after the statement is executed will return the last identification value generated by the trigger. If the INSERT or SELECT INTO statement fails or mass replication fails, or if the transaction is rolled back, the @@IDENTITY value is not restored to its previous settings.

OUTPUT INSERTED

For INSERT, you can reference the inserted table to query the properties of the new row

The test code is as follows:


The effect is as follows:







Previous:MSSQL conditional query WHERE ignores the condition
Next:Baidu map point aggregation
 Landlord| Posted on 7/7/2020 1:22:22 PM |
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