Let's say my table structure looks something like this:
CREATE TABLE [dbo].[table1] ( [id] [int] IDENTITY(1,1) NOT NULL, [data] [varchar](255) NOT NULL, CONSTRAINT [PK_table1] PRIMARY KEY CLUSTERED ([id] ASC) ) CREATE TABLE [dbo].[table2] ( [id] [int] IDENTITY(1,1) NOT NULL, [table1_id] [int] NOT NULL, [data] [varchar](255) NOT NULL, CONSTRAINT [PK_table2] PRIMARY KEY CLUSTERED ([id] ASC) )
The [id] field of the first table corresponds to the [table1_id] field of the second. What I would like to do is insert data into both tables in one transaction. Now I already know how to do this by doing INSERT-SELECT-INSERT, for example:
BEGIN TRANSACTION; DECLARE @id [int]; INSERT INTO [table1] ([data]) VALUES ('row 1'); SELECT @id = SCOPE_IDENTITY(); INSERT INTO [table2] ([table1_id], [data]) VALUES (@id, 'more of row 1'); COMMIT TRANSACTION;
This is all good and perfect for small cases, for example, where you only insert maybe a few lines. But I need to insert a couple of hundred thousand lines, or maybe even a million lines, all at once. The data comes from another table, so if I only inserted it into one table, it would be simple, I just would have to do this:
INSERT INTO [table] ([data]) SELECT [data] FROM [external_table];
But how would I do this and split the data into [table1] and [table2] and still update [table2] with the corresponding [table1_id] , how do I do it? Is it possible?
sql sql-server tsql insert foreign-keys
soapergem Sep 14 2018-10-10T00: 00Z
source share