gpt4 book ai didi

sql - 将标识列值从另一个表插入到表中?

转载 作者:行者123 更新时间:2023-12-04 23:17:20 25 4
gpt4 key购买 nike

create table #test (a int identity(1,1), b varchar(20), c varchar(20))

insert into #test (b,c) values ('bvju','hjab')
insert into #test (b,c) values ('bst','sdfkg')
......
insert into #test (b,c) values ('hdsj','kfsd')

我如何将从上述插入语句填充的标识值( #test.a )插入到 #sample 中 table (另一张 table )
create table #sample (d int identity(1,1), e int, f varchar(20))

insert into #sample(e,f) values (identity value from #test table, 'jkhjk')
insert into #sample(e,f) values (identity value from #test table, 'hfhfd')
......
insert into #sample(e,f) values (identity value from #test table, 'khyy')

任何人都可以解释我如何为更大的记录集(数千条记录)实现这一点?

我们可以使用 while循环和 scope_identity ?如果是这样,请解释我们该怎么做?

如果我从选择查询插入 #test 会出现什么情况?

插入#test (b,c)
select ... from ...(数千条记录)

我将如何捕获身份值并将该值用于另一个(#sample)
插入#sample(e,f)
选择(来自#test 的身份值),......来自......(数千条记录)——

最佳答案

您可以使用 output 条款。从文档(强调我的):

The OUTPUT clause returns information from, or expressions based on, each row affected by an INSERT, UPDATE, DELETE, or MERGE statement. These results can be returned to the processing application for use in such things as confirmation messages, archiving, and other such application requirements. The results can also be inserted into a table or table variable. Additionally, you can capture the results of an OUTPUT clause in a nested INSERT, UPDATE, DELETE, or MERGE statement, and insert those results into a target table or view.



像这样:
create table #tempids (a int) -- a temp table for holding our identity values

insert into #test
(b,c)
output inserted.a into #tempids -- put the inserted identity value into #tempids
values
('bvju','hjab')

然后你问...

What if the insert is from a select instead?



它的工作方式相同......
insert into #test 
(b,c)
output inserted.a into #tempids -- put the inserted identity value into #tempids
select -- except you use a select here
Column1
,Column2
from SomeSource

无论是从值、派生表、执行语句、dml 表源还是默认值插入,它的工作方式都相同。 如果您插入 1000 条记录,您将在 #tempids 中获得 1000 个 ID。 .

关于sql - 将标识列值从另一个表插入到表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17662432/

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