I come, I see, I conquer

                    —Gaius Julius Caesar

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

 

表t1(右),t2(右)如下,结构相同,只是数据有差异,关键字为pid:

          

 

现在想要找出不同时存在于两个表的记录,即t1较t2多出的记录,以及t2较t1多出的记录。我们用NOT EXISTS语句。

 

/*in t1 but not in t2*/
select *
from t1
where 
not exists
(
select *
from t2
where t1.pid = t2.pid
);

结果如下:

 

/*in t2 but not in t1*/
select *
from t2
where 
not exists
(
select *
from t1
where t1.pid = t2.pid
);

结果如下:

 

题外:如果字段pid的数据类型为ntext,则需要用cast映射成nvarchar,用以下sql语句

select *
from bad
where 
not exists
(
select *
from good
where cast(bad.pid as nvarchar(max)) = cast(good.pid as nvarchar(max))
);

 

posted on 2013-08-09 16:34  jcsu  阅读(587)  评论(0)    收藏  举报