IF OBJECT_ID(‘[A]’) IS NOT NULL
DROP TABLE [A]
GO
CREATE TABLE [A] ([id] [int],[name] [nvarchar](10),[yoyo] [nvarchar](10))
INSERT INTO [A]SELECT ‘2’,’name2′,’x张三’ union all
SELECT ‘3’,’name2′,’李四’ union all
SELECT ‘2’,’name3′,’李四’
IF OBJECT_ID(‘[B]’) IS NOT NULL
DROP TABLE [B]
GO
CREATE TABLE [B] ([id] [int],[name] [nvarchar](10),[yoyo] [nvarchar](10))
INSERT INTO [B] SELECT ‘2’,’name2′,’张三’ UNION ALL
SELECT ‘2’,’name2′,’李四’ union all
SELECT ‘2’,’name3′,’李四’
–>SQL查询如下:
select * from A
select * from B
select * from (
SELECT * FROM ( SELECT ‘B表’ AS 表名, id FROM [B] EXCEPT SELECT ‘B表’ AS 表名, id FROM [A] ) a
UNION ALL
SELECT * FROM ( SELECT ‘A表’ AS 表名, id FROM [A] EXCEPT SELECT ‘A表’ AS 表名, id FROM [B] ) b
) c
/*表名 id name yoyo—- ———– ———- ———-B表 3 name3 李四(1 行受影响)*/
IF OBJECT_ID('[A]') IS NOT NULL DROP TABLE [A] GO CREATE TABLE [A] ([id] [int],[name] [nvarchar](10),[yoyo] [nvarchar](10)) INSERT INTO [A]SELECT '2','name2','x张三' union all SELECT '3','name2','李四' union all SELECT '2','name3','李四' IF OBJECT_ID('[B]') IS NOT NULL DROP TABLE [B] GO CREATE TABLE [B] ([id] [int],[name] [nvarchar](10),[yoyo] [nvarchar](10)) INSERT INTO [B] SELECT '2','name2','张三' UNION ALL SELECT '2','name2','李四' union all SELECT '2','name3','李四' -->SQL查询如下: select * from A select * from B select * from ( SELECT * FROM ( SELECT 'B表' AS 表名, id FROM [B] EXCEPT SELECT 'B表' AS 表名, id FROM [A] ) a UNION ALL SELECT * FROM ( SELECT 'A表' AS 表名, id FROM [A] EXCEPT SELECT 'A表' AS 表名, id FROM [B] ) b ) c /*表名 id name yoyo---- ----------- ---------- ----------B表 3 name3 李四(1 行受影响)*/