我有两张桌子:
Table1
:
RulesVectorID(nullable, primary),Weight,IsDeleted
Table2
:
RulesVectorID(forigen) , Weight,IsDeleted, NumberOfOffers, other fields...
我想做两件事:
将Id
分配给table1 where RulesVectorID ==null
我试过了:
UPDATE myTable1
SET RulesVectorID = SELECT MAX(RulesVectorID) + 1 FROM myTable1,
WHERE RulesVectorID IS NULL
对于在步骤(1)中添加的行,我想复制他们的Weight, IsDeleted
列,并在他们的NumberOfOffers
我试过了:
INSERT INTO myTable2 (Weight, IsDeleted, NumberOfOffers, RulesVectorID)
VALUES (
SELECT Weight, IsDeleted, 1, RulesVectorID
FROM myTable1
WHERE myTable1.RulesVectorID NOT IN (SELECT RulesVectorID FROM myTable2))
有没有更干净的方法呢?
答案 0 :(得分:1)
假设您在每个表中的[uniqueID]列都有一个索引,并且您只想用表2中的数据更新表1中的现有行,并且两个表之间的[uniqueID]应该是相同的,您可以尝试以下内容:
UPDATE Table1
SET Table1.stfips=Table2.NEWstfips,
Table1.areatype=Table2.NEWareatype,
Table1.area=Table2.NEWarea
FROM Table2
JOIN Table1
ON Table1.uniqueid=Table2.uniqueid
我们在我们的临时数据库中使用它,因此速度不是很重要。对1300万条记录进行包络测试后,我们的硬件(YMMV)需要大约15秒钟。
答案 1 :(得分:0)
;with t as (
select *, rn=row_number() over (order by weight)
from mytable1
where RulesVectorID is null)
update t set RulesVectorID = rn + isnull((Select max(RulesVectorID) from myTable1),0);
删除values()
insert into myTable2 (Weight,IsDeleted,NumberOfOffers,RulesVectorID)
select Weight,IsDeleted,1,RulesVectorID
from myTable1
where myTable1.RulesVectorID not in (select RulesVectorID from myTable2)