添加引用标识列的列

时间:2016-03-16 16:33:26

标签: sql-server

在我的表table1中,我添加了taxonomy_idtaxonomy_idtaxonomy列,该列是一个标识列。 现在我需要插入尽可能多的taxonomy个记录,因为表table1中有记录,我需要相应地更新table1.taxonomy_id以引用taxonomy.taxonomy_id

我如何在SQL Server中执行此操作?我可以运行游标,逐行插入行并使用scope_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)

2 个答案:

答案 0 :(得分:0)

output

insert into table1 (col1, col2) values (2,3), ...  
output inserted.iden

我没有按照你的插入细节,但上面是获取识别

的机制

??

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

答案 1 :(得分:0)

这就是我所做的:

-- 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表中的记录。