Home > Database > Mysql Tutorial > How Can I Retrieve Identity Values After Bulk Inserts in SQL Server 2005?

How Can I Retrieve Identity Values After Bulk Inserts in SQL Server 2005?

Linda Hamilton
Release: 2024-12-29 14:05:11
Original
827 people have browsed it

How Can I Retrieve Identity Values After Bulk Inserts in SQL Server 2005?

Getting Identity Values During Bulk Inserts in SQL Server 2005

When inserting multiple records from one table to another, it can be useful to obtain the identity values assigned to the newly inserted records. This allows for efficient updates to the source table with foreign keys referencing the target table.

Inserting Records and Retrieving Identity Values

In this case, we want to insert records from table B into table A and retrieve the identity values of the newly inserted records for updating field "NewId" in table B.

Using the OUTPUT Clause

MS SQL Server 2005 provides the OUTPUT clause that allows users to capture the values inserted during a data modification operation. In this case, we can use it as follows:

DECLARE @output TABLE (id int)

Insert into A (fname, lname)
OUTPUT inserted.ID INTO @output
SELECT fname, lname FROM B

select * from @output
Copy after login

By using the OUTPUT clause, we create a table variable @output to store the identity values. The inserted.ID refers to the identity value of the newly inserted record in table A.

After executing the insert statement, the @output table will contain the identity values corresponding to the rows inserted from table B. You can then use these values to update the NewId field in table B without the need for cursors.

The above is the detailed content of How Can I Retrieve Identity Values After Bulk Inserts in SQL Server 2005?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template