如何确保将所有行插入到数据模型中,然后截断登台表

时间:2014-05-09 02:53:20

标签: sql sql-server

在我的ETL作业中,我想截断stg表,但在截断stging表之前,我想确保所有记录都插入到数据模型中。 样本如下

create table #stg (
    CreateID int,
    Name nvarchar(10)
)
insert into #stg
select 1, 'a' union all
select 2, 'b' union all
select 3, 'c' union all
select 4, 'd' 

go

create table #Approve1 (
    CreateID int,
    Name nvarchar(10)
)
insert into #Approve1 
select 1, 'a' union all
select 4, 'd' 

create table #Approve2 (
    CreateID int,
    Name nvarchar(10)
)
insert into #Approve2
select 3, 'c'

create table #Reject (
    CreateID int,
    Name nvarchar(10)
)
insert into #Reject
select 2, 'b'



select * from #stg
select * from #Approve1
select * from #Approve2
select * from #Reject`

如何在这些表中进行检查,并确保将所有值都加载到数据模型中,并且可以截断临时表。

由于

1 个答案:

答案 0 :(得分:0)

您可以检查至少其中一个表中是否存在这些值。这是一个使用not exists计算登台表中剩余记录数的方法:

select count(*)
from #stg s
where not exists (select 1 from #Approve1 a where a.CreateId = s.CreateId and a.name = s.name) and
      not exists (select 1 from #Approve2 a where a.CreateId = s.CreateId and a.name = s.name) and
      not exists (select 1 from #Reject r where r.CreateId = s.CreateId and r.name = s.name);

如果返回的值大于0,则不会插入所有内容。 (通过使用select *,您可以看到缺少的内容。)

当然,这并不能保证你想要什么,因为这些值可能早先存在于表中。我假设这是一个简化的表结构,你有一些机制来识别最近插入的记录。