日期:2014-05-18  浏览次数:20974 次

SQL语句判断空值相等
SQL code
 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) 


上面是在论坛上看到一个比对表内容变化的例子,可以精确到每个字段。

现在出现一个问题就是如果 某一个字段 在两个表中都为空 用 a.t4=b.t4 的话 两个字段不相等,虽然没有做任何更改,仍然得到了这个记录。因为NULL 的判断不能用=号 要用 IS NULL 。
有没有解决这个问题的方法? 就是两个字段都为NULL的时候不让出现在这个结果里

还有,如果有更好的比对两个表的方法也烦请回答下, 要求能得到的结果 A表 和 B表相比 B新增加的,B修改过的 记录集。 然后我可以用程序反映到A表去。 单独开贴200分奉上。

------解决方案--------------------
在两个表中都为空 用 a.t4=b.t4 的话 两个字段不相等


SQL code
isnull(a.t4,'')=isnull(b.t4,'')

------解决方案--------------------
SQL code
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
*/