SQL Server UNION
UNION是并集,是把两个集合中所有元素的集合。
集合运算有两个选项,即是DISTINCT和ALL, 当您使用 UNION时,也等于UNION DISTINCT,这个选项的结果,是消除重复的记录行,返回一个集合。而后者UNION ALL则是返回多集中所有记录行。
下面演示UNION(DISTINCT),
为了演示,首选创建两个变量表,并插入数据:
第一个表:
代码
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');
UNION运算:
SELECT * FROM @T1
UNION
SELECT * FROM @T2
UNION
SELECT * FROM @T2
结果:
下面演示UNION ALL,插入的数据有重复的,注意一下Query的结果
SELECT * FROM @T1
UNION ALL
SELECT * FROM @T2
UNION ALL
SELECT * FROM @T2