不要使用两个表并切换视图,而是使用一个主表和一个临时表。
当您准备好将数据迁移到主表时,您可以像这样在原子事务中执行此操作。
begin try
begin tran
delete * from MainTable with (tablockx)
insert MainTable
select * from StagingTable with (tablockx)
commit
end try
begin catch
rollback
raiserror('An error occurred swapping staging data', 16,16)
end catch
这样一来,您始终在临时表上工作,因此识别要使用的正确表没有困难。
根据数据,您可能希望对主表进行增量更新:
-- delete rows which no longer exist
delete MainTable
from MainTable
where not exists (select 1 from StagingTable where StagingTable.primaryKey = MainTable.primaryKey)
-- Insert new rows
insert MainTable
select *
from StagingTable
where not exists (select 1 from MainTable where StagingTable.primaryKey = MainTable.primaryKey)
-- update rows which have changed
update MainTable
set
col1 = stagingTable.col1,
col2 = stagingTable.col2
from MainTable inner join StagingTable on StagingTable.primaryKey = MainTable.primaryKey
where 1=2
-- Need to compare every column, only update if one is different
-- Both null counts as the same - compare nullity
OR case when MainTable.col1 is null then 0 else 1 end <> case when StagingTable.col1 is null then 0 else 1 end
OR MainTable.col1 <> StagingTable.col1
OR case when MainTable.col2 is null then 0 else 1 end <> case when StagingTable.col2 is null then 0 else 1 end
OR MainTable.col2 <> StagingTable.col2