注意此语法仅在SQL Server 2005及以上版本支持。
1.区别
EXCEPT是指在第一个集合中存在,但是不存在于第二个集合中的数据。
INTERSECT返回由两个集合中都存在的数据
2.注意事项
(1).使用SQL Server 2005 EXCEPT或INTERSECT比较的结果集必须具有相同的结构。它们的列数必须相同,并且相应的结果集列的数据类型必须兼容
(2).INTERSECT运算符优先于EXCEPT
(3).Select INTO必须是包含INTERSECT或EXCEPT运算符的语句中的第一个查询,用来创建容纳最终结果集的表
(4).ORDER BY子句中的列名或别名必须引用左侧查询返回的列名
3.测试如下:
create table A1(id int,mark char(2))
go
create table A2(id int,mark char(2))
go
insert into A1
select 1,'t1' union all
select 2,'t2' union all
select 3,'t3' union all
select 4,'t4'
go
insert into A2
select 2,'t2' union all
select 3,'m3' union all
select 5,'m5' union all
select 6,'t6'
go
select * from A1
EXCEPT
select * from A2
go
select * from A1
INTERSECT
select * from A2
go
--EXCEPT结果集为
--1 t1
--3 t3
--4 t4
--INTERSECT结果集为
--2 t2