-1

我有 2 个 Excel 文件作为两个表导入到 MS Access 中。这两个表相同,但在不同日期导入。

现在,我怎样才能知道以后更新了哪些行和哪些字段?任何帮助将不胜感激。

4

4 回答 4

1

查找插入的记录很容易

select * from B where not exists (select 1 from A where A.pk=B.pk)

查找已删除的记录同样简单

select * from A where not exists (select 1 from B where A.pk=B.pk)

查找更新的记录很痛苦。以下严格查询假设您有可为空的列,并且它应该适用于所有情况。

select B.*
  from B
  inner join A on B.pk=A.pk
 where A.col1<>B.col1 or (IsNull(A.col1) and not IsNull(B.col1)) or (not IsNull(A.col1) and  IsNull(B.col1))
    or A.col2<>B.col2 or (IsNull(A.col2) and not IsNull(B.col2)) or (not IsNull(A.col2) and  IsNull(B.col2))
    or A.col3<>B.col3 or (IsNull(A.col3) and not IsNull(B.col3)) or (not IsNull(A.col3) and  IsNull(B.col3))
    etc...

如果列被定义为 NOT NULL 则查询要简单得多,只需删除所有 NULL 测试。

如果列可以为空,但您可以确定一个永远不会出现在数据中的值,则使用简单的比较,例如:

Nz(A.col1,neverAppearingValue)<>Nz(B.col1,neverAppearingValue)
于 2012-06-29T14:49:16.970 回答
0

我相信这应该像运行这样的查询一样简单:

SELECT * 
FROM Table1
    JOIN Table2
         ON Table1.ID = Table2.ID AND Table1.Date != Table2.Date
于 2012-06-29T13:43:00.410 回答
0

一种方法是取消透视两个表,因此您会得到一个带有 , , 的新表。但请注意,您必须考虑类型。

例如,以下获取字段的差异:

with oldt as (select id, col, val
              from <old table> t
              unpivot (val for col in (<column list>)) unpvt
             ),
     newt as (select id, col, val
              from <new table> t
              unpivot (val for col in (<column list>)) unpvit
             )
select *
from oldt full outer join newt on oldt.id = newt.id
where oldt.id is null or newt.id is null

连接的替代方法相当麻烦。此版本显示是否添加、删除了列以及更改了哪些列(如果有):

select *
from (select coalesce(oldt.id, newt.id) as id,
             (case when oldt.id is null and newt.id is not null then 'ADDED'
                   when oldt.id is not null and newt.id is null then 'DELETED'
                   else 'SAME'
              end) as stat,
             (case when oldt.col1 <> newt.col1 or oldt.col1 is null and newt.col1 is null
                   then 1 else 0 end) as diff_col1,
             (case when oldt.col2 <> newt.col2 or oldt.col2 is null and newt.col2 is null
                   then 1 else 0 end) as diff_col2,
             ...
      from <old table> oldt full outer join <new table> newt on oldt.id = newt.id
     ) c
where status in ('ADDED', 'DELETED') or
     (diff_col1 + diff_col2 + ... ) > 0

它确实具有适用于任何数据类型的优势。

于 2012-06-29T14:01:39.713 回答
0
(Select * from OldTable Except Select *from NewTable)
Union All
(Select * from NewTable Except Select *from OldTable)
于 2012-07-16T13:53:26.387 回答