日期:2014-05-18 浏览次数:21149 次
 Create   Table   testa(t1   varchar(10),t2   varchar(10),t3   varchar(10),t4   varchar(10))   
  Create   Table   testb(t1   varchar(10),t2   varchar(10),t3   varchar(10),t4   varchar(10))   
    
  Insert   into   testa   select   'hello','11','441','441'   
  union   select   'word','21','441','441'   
  union   select   'word','21','442','442'   
  union   select   'word2','212','442','442'   
    
  Insert   into   testb   select   'hello','11','xxx','xxxx'     
  union   select   'word','21','xxx','xxxx'   
select * from testa
select   *   from   testb   
select   *   from   testa   a where not exists(select * from testb b where a.t1=b.t1 and a.t2=b.t2 and a.t3=b.t3 and a.t4=b.t4) 
isnull(a.t4,'')=isnull(b.t4,'')
------解决方案--------------------
if object_id('tempdb.dbo.#1') is not null drop table #1
if object_id('tempdb.dbo.#2') is not null drop table #2
create table #1 (c1 varchar(10), c2 varchar(10))
insert into #1 select 'a', null
insert into #1 select 'b', null
insert into #1 select 'c', '1'
create table #2 (c1 varchar(10), c2 varchar(10))
insert into #2 select 'a', null
insert into #2 select 'b', ''
insert into #2 select 'c', '1'
insert into #2 select 'd', '2'
insert into #2 select 'e', '3'
--> 2005 很简单,不必担心NULL值得问题:
select * from #2 except select * from #1
/*
c1         c2
---------- ----------
b          
d          2
e          3
*/
--> 这是楼主提供的写法
select * from #2 a where not exists (select 1 from #1 where c1=a.c1 and c2=a.c2)
/*
c1         c2
---------- ----------
a          NULL
b          
d          2
e          3
*/
--> 看看isnull的写法,因为isnull的替换值无法预期,这种写法不完善,如c1='b'的纪录被排除在外:
select * from #2 a where not exists (select 1 from #1 where isnull(c1,'')=isnull(a.c1,'') and isnull(c2,'')=isnull(a.c2,''))
/*
c1         c2
---------- ----------
d          2
e          3
*/
--> 2000
select * from #2 a where not exists (select 1 from #1 where (c1=a.c1 or isnull(c1,a.c1) is null) and (c2=a.c2 or isnull(c2,a.c2) is null))
/*
c1         c2
---------- ----------
b          
d          2
e          3
*/