日期:2014-05-17  浏览次数:20604 次

基础问题:两表比较是否相等?
SQL code

--两个表A,B。使用下述语句判断,显示‘不等’
select Matchtype= case when (SELECT CHECKSUM_AGG (BINARY_CHECKSUM (*)) FROM A) 
             = 
             (SELECT CHECKSUM_AGG (BINARY_CHECKSUM (*)) FROM  B) then 'Equal'
        else 'Not Equal'
        end

--但是,使用下面语句时,显示记录条数相等。这是为什么呢?
select count(1) from
(select * from A
  union
  select * from B)fin
select count(1) from A



------解决方案--------------------
举个反例,证明之.
SQL code

declare @a table(id int,de nchar(500))
declare @b table(id int,de varchar(5))

insert into @a values(1,null),(2,'bbb'),(2,'bbb')
insert into @b values(1,null),(11,null),(2,'bbb')


select count(1) from @a
--> 3

select count(1) from @b
--> 3

select count(1) 
from
(select * from @a
 union
 select * from @b) fin
--> 3

select Matchtype=
       case when (select checksum_agg(binary_checksum(*)) from @a) 
                  =
                 (select checksum_agg(binary_checksum(*)) from @b) 
            then 'Equal' else 'Not Equal'
       end
--> Not Equal