Sql server 添加引用标识列的列
在我的表Sql server 添加引用标识列的列,sql-server,Sql Server,在我的表table1中,我添加了一列taxonomy\u id引用taxonomy\u id列,该列是一个标识列。 现在,我需要插入尽可能多的taxonomy记录,就像表table1中的记录一样,并且我需要更新table1.taxonomy\u id以引用taxonomy.taxonomy\u id 如何在SQL server中实现这一点?我可以运行一个游标,逐个插入行,然后使用scope\u identity(),但这是唯一的解决方案吗 示例数据集和结构: --drop table taxon
table1
中,我添加了一列taxonomy\u id
引用taxonomy\u id
列,该列是一个标识列。
现在,我需要插入尽可能多的taxonomy
记录,就像表table1
中的记录一样,并且我需要更新table1.taxonomy\u id
以引用taxonomy.taxonomy\u id
如何在SQL server中实现这一点?我可以运行一个游标,逐个插入行,然后使用scope\u identity()
,但这是唯一的解决方案吗
示例数据集和结构:
--drop table taxonomy
create table taxonomy(taxonomy_id int identity, data varchar(50))
--drop table table1
create table table1(table1_id int, taxonomy_id int)
insert into table1 (table1_id) values (999), (777), (555), (22), (54423)
我没有按照你的插入细节,但上面是获得iden的机制
?
这就是我所做的:
-- declare a temp table
declare @temptab table(taxonomy_id int);
-- insert new rows into taxonomy table
-- return the IDs so we know which ones are the new ones
insert into taxonomy(data)
output inserted.taxonomy_id into @temptab
select 'table1 taxonomy data' from table1
-- update table1 with the IDs from the temp table
update table1
set taxonomy_id = t2.taxonomy_id
from (
-- using the row_number makes little sense but..
-- I needed a way to pair @temptab and table1 rows
select table1_id, ROW_NUMBER() over (order by table1_id) from table1
) t1(table1_id, rownum)
inner join (
select taxonomy_id, ROW_NUMBER() over (order by taxonomy_id) from @temptab
) t2(taxonomy_id, rownum)
on t1.rownum = t2.rownum
where table1.table1_id = t1.table1_id
现在,每个
table1
记录都连接到taxonomy
表中的一个记录。请参阅输出,欢迎使用。恐怕这个问题没有给我太多的帮助。
insert into taxonomy (col1, col2)
select col1, col2 from table1
output inserted.id, inserted.col1, inserted.col2
update table1
set table1.taxonomy_id = inserted.id
from table1
join inserted
on inserted.col1 = table1.col1
and inserted.col2 = table1.col2
-- declare a temp table
declare @temptab table(taxonomy_id int);
-- insert new rows into taxonomy table
-- return the IDs so we know which ones are the new ones
insert into taxonomy(data)
output inserted.taxonomy_id into @temptab
select 'table1 taxonomy data' from table1
-- update table1 with the IDs from the temp table
update table1
set taxonomy_id = t2.taxonomy_id
from (
-- using the row_number makes little sense but..
-- I needed a way to pair @temptab and table1 rows
select table1_id, ROW_NUMBER() over (order by table1_id) from table1
) t1(table1_id, rownum)
inner join (
select taxonomy_id, ROW_NUMBER() over (order by taxonomy_id) from @temptab
) t2(taxonomy_id, rownum)
on t1.rownum = t2.rownum
where table1.table1_id = t1.table1_id