SQL Server EXCEPT
EXCEPT(差集)集合运算, 对两个输入查询的结果集合进行操作,返回出现第一个结果集中,但不出现在第二个结果集中的所有行。
为了演示,首选创建两个变量表,并插入数据:
第一个表:
代码
DECLARE @T1 AS TABLE(ColName1 NVARCHAR(50),ColName2 NVARCHAR(50))
INSERT INTO @T1 VALUES ('tc1','tc2');
INSERT INTO @T1 VALUES ('tc3','tc4');
INSERT INTO @T1 VALUES ('tc5','tc6');
INSERT INTO @T1 VALUES ('tc13','tc14');
INSERT INTO @T1 VALUES ('tc1','tc2');
INSERT INTO @T1 VALUES ('tc3','tc4');
INSERT INTO @T1 VALUES ('tc5','tc6');
INSERT INTO @T1 VALUES ('tc13','tc14');
第二个表:
代码
DECLARE @T2 AS TABLE(ColName1 NVARCHAR(50),ColName2 NVARCHAR(50))
INSERT INTO @T2 VALUES ('tc1','tc2');
INSERT INTO @T2 VALUES ('tc3','tc4');
INSERT INTO @T2 VALUES ('tc9','tc10');
INSERT INTO @T2 VALUES ('tc7','tc8');
INSERT INTO @T2 VALUES ('tc1','tc2');
INSERT INTO @T2 VALUES ('tc3','tc4');
INSERT INTO @T2 VALUES ('tc9','tc10');
INSERT INTO @T2 VALUES ('tc7','tc8');
EXCEPT差集运算:
SELECT * FROM @T1
EXCEPT
SELECT * FROM @T2
EXCEPT
SELECT * FROM @T2
结果:
为了更清楚,现把EXCEPT差集运算的两个表对调一下,
SELECT * FROM @T2
EXCEPT
SELECT * FROM @T1
EXCEPT
SELECT * FROM @T1
结果: