SQLServer两张表筛选相同数据和不同数据

概述

项目中经常会对两张数据库表的数据进行比较,选出相同的数据或者不同的数据。在SQL SERVER 2000中只能用Exists来判断,到了SQL SERVER 2005以后可以采用EXCEPT和INTERSECT运算符比较两张表的数据。

EXCEPT运算符返回由EXCEPT运算符左侧的查询返回、而又不包含在右侧查询所返回的值中的所有非重复值。

INTERSECT返回由INTERSECT运算符左侧和右侧的查询都返回的所有非重复值。

例如有表A和B,其建表和数据脚本如下:

if object_id('[a]') is not null drop table [a]
go 
create table [a]([tel_no] bigint,[cost] int)
insert [a]
select 13800000000,38 union all
select 13823400000,56 union all
select 13800056400,88 union all
select 13800230000,28 union all
select 13802300000,18 union all
select 13822220000,68 union all
select 13844400000,98 union all
select 13833330000,35 union all
select 13822220000,31 union all
select 13811110000,32
--> 测试数据:[b]
if object_id('[b]') is not null drop table [b]
go 
create table [b]([tel_no] bigint)
insert [b]
select 13800000000 union all
select 13823400000 union all
select 13800051230 union all
select 13800230123

现在要查出两张表相同的数据和两张表不同的数据,如果在SQL SERVER 2005以上版本:

--相同数据
select tel_no  
from a
intersect
select tel_no 
from b

--不同数据
select tel_no  
from b
except
select tel_no 
from a

如果是SQL SERVER 2000

SELECT * FROM b WHERE EXISTS(SELECT 1 FROM a WHERE tel_no=b.tel_no)
 
SELECT * FROM b WHERE NOT EXISTS(SELECT 1 FROM a WHERE tel_no=b.tel_no)
原文地址:https://www.cnblogs.com/sunxuchu/p/5433882.html