Search code examples
c#sql-serverstored-procedurestransactionsmaster-detail

SQL Server and C# Master / Detail Insert


I am creating stored procedures that will be called from my C# application and will enter master/detail information into SQL Server. On the Header table I have TransactionId as an Identity column so that I get a unique ID every time I insert. When I call my stored procedure for the detail table, I would like to use the PK ID from the Header and insert it into the FK of the detail. What is the best way to ensure that I get back the ID that was just created in the Header table?

CREATE TABLE [dbo].[Header835]
(
   [TRANSACTIONID] [int] IDENTITY(1, 1) NOT NULL
   , [FILENAME] [varchar](80) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
   , [TRADINGPARTNERNAME] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
   , [ISACRTL] [numeric](18, 0) NOT NULL
   , [STCRTL] [numeric](18, 0) NOT NULL
   , CONSTRAINT [PK_Header835] PRIMARY KEY CLUSTERED
   (
      [TRANSACTIONID] ASC
   ) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

Solution

  • You'll wan to use SCOPE_IDENTITY()

    DECLARE @headerTransactionId INT;
    
    INSERT INTO dbo.Header835(Filename, TradingPartnerName, IsACrtl, StCrtl)
    SELECT 'myFile.txt', 'Joe', 103, 123;
    
    SELECT @headerTransactionId = SCOPE_IDENTITY();    
    

    SQL Fiddle Example