Home > Transact SQL > Insert to another table after inserting to a table

Insert to another table after inserting to a table

This is quite an often question asked by people.
There are 2 options. Create a stored procedure with 2 steps
something like

This is quite an often question asked by people.
There are 2 options. Create a stored procedure with 2 steps something like. It’ll insert the last value inserted to table A to table B

CREATE PROCEDURE InsertInsert

AS BEGIN

declare @id int
Insert to table A
select 'A', 'B'

--take the last id inserted
SET @id = @@identity

GO

Insert to table B
Select Col1, Col2 from Table A
where ID = @id

END

or you can use trigger.

CREATE TRIGGER InsertToOtherTable
ON TableSource
AFTER INSERT
AS
INSERT INTO TableB
SELECT Col1, Col2
FROM INSERTED

BOL

Advertisement
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.