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

标签 sql sql-server

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/

相关文章:

php - 为什么我收到 "You have an error in your SQL syntax"错误?

sql-server - SQL Server 在组合键上自动递增

sql - 如何只选择重复的记录?

sql - 从远程服务器检索数十亿行?

javascript - SQL 语句中单引号替换的正则表达式

sql-server - 如何将 SQL Server 的结果 - "New Data Comparison"导出到 Excel 文件?

MySQL 查询与内连接返回空集

php - 在准备好的语句中不工作标记

mysql - 如何使用 INSERT ... ON DUPLICATE?

mysql - 使用(或不使用)联结表