I'm inserting multiple records into a table A from another table B. Is there a way to get the identity value of table A record and update table b record with out doing a cursor?
Create Table A
(id int identity,
Fname nvarchar(50),
Lname nvarchar(50))
Create Table B
(Fname nvarchar(50),
Lname nvarchar(50),
NewId int)
Insert into A(fname, lname)
SELECT fname, lname
FROM B
I'm using MS SQL Server 2005.
Once we insert a row in a table, the @@IDENTITY function column gives the IDENTITY value generated by the statement. If we run any query that did not generate IDENTITY values, we get NULL value in the output. The SQL @@IDENTITY runs under the scope of the current session.
To do this before you enter the while loop you can get the maximum number ( select max(id) from tablename ), increment it by one and then insert it within the while loop.
INSERT-SELECT-UNION query to insert multiple records Thus, we can use INSERT-SELECT-UNION query to insert data into multiple rows of the table. The SQL UNION query helps to select all the data that has been enclosed by the SELECT query through the INSERT statement.
Use the ouput clause from 2005:
DECLARE @output TABLE (id int)
Insert into A (fname, lname)
OUTPUT inserted.ID INTO @output
SELECT fname, lname FROM B
select * from @output
now your table variable has the identity values of all the rows you insert.
Reading your question carefully, you just want to update table B based on the new identity values in table A.
After the insert is finished, just run an update...
UPDATE B
SET NewID = A.ID
FROM B INNER JOIN A
ON (B.FName = A.Fname AND B.LName = A.LName)
This assumes that the FName / LName combination can be used to key match the records between the tables. If this is not the case, you may need to add extra fields to ensure the records match correctly.
If you don't have an alternate key that allows you to match the records then it doesn't make sense at all, since the records in table B can't be distinguished from one another.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With