用示例讨论一个子查询问题,存在 null 将导致结果不对
就是下面这个例子,如果记录中存在 null记录,则结果是不对的.
其实我们想得到的结果是 c
但是在删除  null 值的记录前,这个结果是得不到的.但是将所有 null 值的记录删除后,就得到正确结果了,
大家说说,这是为什么,如何避免这种情况出现呢?
IF OBJECT_ID('tb') IS NOT NULL
  DROP TABLE tb
GO
CREATE TABLE tb(a varchar(9))
go
insert into tb
select  'a' union all
select  'b' union all
select  NULL union all
select 'c'go
IF OBJECT_ID('tb1') IS NOT NULL
  DROP TABLE tb1
GO
CREATE TABLE tb1(a varchar(9))
go
insert into tb1
select  'a' union all
select null union all
select 'b'
goselect * from tb
select * from tb1--此时存在 null 值的记录
select a as 删除null前 from tb where a not in (select a from tb1 )/* --此时没有记录,可是我们想得到的结果是 c
a         
--------- (所影响的行数为 0 行)
*/delete tb
where a is nulldelete tb1
where a is null
select * from tb
select * from tb1
--此时没有null
select a as 删除null后 from tb where a not in (select a from tb1 )/* --此时就有记录了
a         
--------- 
c(所影响的行数为 1 行)
*/

解决方案 »

  1.   

    select a as 删除null前 from tb where isnull(a,'') not in (select isnull(a,'') from tb1 )
      

  2.   

    用isnull(a,'')将null替换为''即可
      

  3.   

    看来 null 的存在有很多不确定性,真不知用 null的好处是什么?
      

  4.   

    按理说,null所占空间应该最小.
      

  5.   

    null值不稳定
    有时对有时不对
    所以建议大家给个默认值  哪怕是''也好