Hi,I need to save two tables in master-detail relation in the same transaction. dbo.Detail table is linked with dbo.Master table via foreign key. Take a look at the example below:CREATE TABLE [dbo].[Master]( [Mas_ID] [int] IDENTITY(1,1) NOT NULL, [Mas_Something] varchar(50) NOT NULL CONSTRAINT [PK_Master] PRIMARY KEY CLUSTERED ( [Mas_ID] ASC )WITH (PAD_INDEX = ON, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 30) ON [PRIMARY],) ON [PRIMARY]CREATE TABLE [dbo].[Detail]( [Det_ID] [int] IDENTITY(1,1) NOT NULL, [Det_MasID] [int] NOT NULL, [Det_Something] varchar(50) NOT NULL CONSTRAINT [PK_Detail] PRIMARY KEY CLUSTERED ( [Det_ID] ASC )WITH (PAD_INDEX = ON, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 40) ON [PRIMARY], CONSTRAINT [FK_Detail_Master] FOREIGN KEY([Det_MasID]) REFERENCES [dbo].[Master] ([Mas_ID])) ON [PRIMARY]BEGIN TRANSACTIONDECLARE @MasID intINSERT INTO dbo.Master([Mas_Something]) VALUES('first item')SET @MasID = (SELECT TOP 1 Mas_ID FROM dbo.Master ORDER BY Mas_ID DESC) --how to find the last item inserted to the dbo.Master in this transaction?INSERT INTO dbo.Detail([Det_MasID], [Det_Something]) VALUES(@MasID, 'first Subitem')IF (@@ERROR <> 0) ROLLBACK TRANSACTIONELSE COMMIT TRANSACTIONSELECT * FROM dbo.MasterSELECT * FROM dbo.DetailMy question is: how to find in optimal way last inserted record into the dbo.Master table?SET @MasID = (SELECT TOP 1 Mas_ID FROM dbo.Master ORDER BY Mas_ID DESC)
I don't think that this is a proper way of doing this.Thanks for your time.