I have two tables: TableA
and TableB
CREATE TABLE TableA (
[TableAId] [int] IDENTITY(1,1) NOT NULL...
CREATE TABLE TableB (
[TableBId] [int] IDENTITY(1,1) NOT NULL,
[TableAID] [int] NOT NULL... -- this is the FK
Question: (as a C# developer)
I am writing a function that INSERTs into TableA
. I need to grab the newly created primary key in TableA
and insert it into the FK of TableB
along with other data.
I've done this before, but I didn't like what I did which is lookup the TableA
PK value immediately after the insert, store it as a variable and then insert it into TableB
.
Can someone show me a more efficient way of doing this? Maybe using scope_identity() in a stored proc? A trigger won't work because I need the new PK back in my C# so I can add additional data before I insert into TableB
. Plus, I want to lock both tables while this runs.
Thank you, Robert