SQL Server and C# Master / Detail Insert

时光怂恿深爱的人放手 提交于 2019-12-11 03:07:13

问题


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]

回答1:


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




回答2:


Check out my blog post about different methods and there advantages and disadvantages here:

http://sqlity.net/en/351/identity-crisis/

In short, you want your code to look like this:

DECLARE @IdentValues TABLE(v INT);

INSERT INTO [dbo].[Header835](<...  column list ...>) 
OUTPUT INSERTED.[TRANSACTIONID] INTO @IdentValues(v)
VALUES(<... value list ...>);

SELECT v AS IdentityValues FROM @IdentValues;



回答3:


Once you have inserted a record in your Header835 table, you get the auto generated identity value of TransactionId with SELECT @@IDENTITY or SELECT SCOPE_IDENTITY(), both will return you the last auto generated identity in the session. You can then use this value in the foreign key of detail records.



来源:https://stackoverflow.com/questions/13058109/sql-server-and-c-sharp-master-detail-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!