I am trying to insert into TableB
and TableC
from TableA
. There are approximately 30 columns in Table A out of which let's say 10 goes to TableB
and 20 goes to TableC
.
The data has to go I believe row by row because. I have to insert one row in TableB
which will generate TableID
as a auto increment PK which is FK in TableC
. I need the TableID
to be inserted with rest of the columns into TableC
.
Below is the code I am using. With this code, my TableB
works fine and all the columns and rows are inserted in TableC
except the ID
is all same in TableC
.
There are thousands of rows in TableA
.
DECLARE @c BIGINT
INSERT INTO dbo.TableB (--TableBId - column value is auto-generated
FirstName, MiddleName, LastName, PhoneNumber,
CreatedBy, Created, Updatedby, Updated, IsActive)
SELECT
MSFIRST, MSMI, MSLAST, MSPHONE,
9999, GETDATE(), 9999, GETDATE(), 1
FROM
TableA
SET @C = SCOPE_IDENTITY()
INSERT INTO [dbo].[TableC] (ClientID, TableBId, SSN,
CreatedBy, Created, UpdatedBy, Updated)
SELECT
400, @C, MSSS,
9999, GETDATE(), 9999, (GETDATE())
FROM
TableA
-- DROP table #tt
SELECT * FROM TableB
SELECT * FROM dbo.TableC