gpt4 book ai didi

sql - 如何在 SQL Server 中同时将数据插入到两个表中?

转载 作者:行者123 更新时间:2023-12-01 17:53:26 29 4
gpt4 key购买 nike

假设我的表结构如下所示:

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)
)

第一个表的 [id] 字段对应于第二个表的 [table1_id] 字段。我想做的是在单个事务中将数据插入到两个表中。现在我已经知道如何通过执行 INSERT-SELECT-INSERT 来做到这一点,如下所示:

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;

对于像您只插入几行的小情况来说,这一切都很好。但我需要做的是一次插入几十万行,甚至可能一百万行。数据来自另一个表,所以如果我只是将其插入到一个表中,那就很容易了,我只需这样做:

INSERT INTO [table] ([data])
SELECT [data] FROM [external_table];

但是我该如何做到这一点并将数据拆分为 [table1][table2],并仍然更新 [table2]我正在做的适当的[table1_id]?这可能吗?

最佳答案

试试这个:

insert into [table] ([data])
output inserted.id, inserted.data into table2
select [data] from [external_table]

更新:回复:

Denis - this seems very close to what I want to do, but perhaps you could fix the following SQL statement for me? Basically the [data] in [table1] and the [data] in [table2] represent two different/distinct columns from [external_table]. The statement you posted above only works when you want the [data] columns to be the same.

INSERT INTO [table1] ([data]) 
OUTPUT [inserted].[id], [external_table].[col2]
INTO [table2] SELECT [col1]
FROM [external_table]

不可能在 insert 语句中输出外部列,所以我认为你可以这样做

merge into [table1] as t
using [external_table] as s
on 1=0 --modify this predicate as necessary
when not matched then insert (data)
values (s.[col1])
output inserted.id, s.[col2] into [table2]
;

关于sql - 如何在 SQL Server 中同时将数据插入到两个表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3712678/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com