转自:http://weblogs.sqlteam.com/jeffs/archive/2004/11/10/2737.aspx
When you have two tables (or resultsets from SELECT statements) that you wish to compare, and you want to see any changes in ANY columns, as well as to see which rows exist in 1 table but not the other (in either direction) I have found that the UNION operator works quite well.

UNION allows you to compare all columns very quickly, and also handles comparing NULL values to other NULLs successfully, which a join clause or a WHERE condition doesn't normally do.  It also allows you to very quickly see which rows are missing in either table, which only a FULL OUTER JOIN will do, but of course we all know to avoid those at all costs (right?) -- a full outer join is about as “unrelational” as you can get.  (every column returned is potentially Null and must be wrapped in a COALESCE function).  Best of all, the UNION is quick and easy and short.

The basic idea is: if we GROUP the union of two tables on all columns, then if the two tables are identical all groups will result in a COUNT(*) of 2.  But for any rows that are not completely matched on any column in the GROUP BY clause, the COUNT(*) will be 1 -- and those are the ones we want.  We also need to add a column to each part of the UNION to indicate which table each row comes from, otherwise there is no way to distinguish between which row comes from which table.

So, here's an example, assuming we are comparing tables A and B, and the primary key of both tables is ID:

SELECT MIN(TableName) as TableName, ID, COL1, COL2, COL3 ...

FROM

(

SELECT 'Table A' as TableName, A.ID, A.COL1, A.COL2, A.COL3, ...

FROM A

UNION ALL

SELECT 'Table B' as TableName, B.ID, B.COL1, B.COl2, B.COL3, ...

FROM B

) tmp

GROUP BY ID, COL1, COL2, COL3 ...

HAVING COUNT(*) = 1

ORDER BY ID

The above returns all rows in either table that do not completely match all columns in the other.  In addition, it returns all rows in either table that do not exist in the other table.  It handles nulls as well, since GROUP BY normally consolidates NULL  values together in the same group.  If both tables match completely, no rows are returned at all.

The MIN() aggregate function used on the TableName column is just arbitrary -- it has no effect since we are only returning groups of rows in which there has been no consolidation with the GROUP BY (note the HAVING clause).

I've posted an implementation of this technique as a stored procedure in the SQLTeam script library section of the forums (http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=23054).  Here it is, below:

CREATE PROCEDURE CompareTables(@table1 varchar(100),

@table2 Varchar(100), @T1ColumnList varchar(1000),

@T2ColumnList varchar(1000) = '')

AS

-- Table1, Table2 are the tables or views to compare.

-- T1ColumnList is the list of columns to compare, from table1.

-- Just list them comma-separated, like in a GROUP BY clause.

-- If T2ColumnList is not specified, it is assumed to be the same

-- as T1ColumnList.  Otherwise, list the columns of Table2 in

-- the same order as the columns in table1 that you wish to compare.

--

-- The result is all rows from either table that do NOT match

-- the other table in all columns specified, along with which table that

-- row is from.

declare @SQL varchar(8000);

IF @t2ColumnList = '' SET @T2ColumnList = @T1ColumnList

set @SQL = 'SELECT ''' + @table1 + ''' AS TableName, ' + @t1ColumnList +

' FROM ' + @Table1 + ' UNION ALL SELECT ''' + @table2 + ''' As TableName, ' +

@t2ColumnList + ' FROM ' + @Table2

set @SQL = 'SELECT Max(TableName) as TableName, ' + @t1ColumnList +

' FROM (' + @SQL + ') A GROUP BY ' + @t1ColumnList +

' HAVING COUNT(*) = 1'

exec ( @SQL)

转载于:https://www.cnblogs.com/jerryhong/archive/2008/01/01/1022195.html

(转载)The shortest, fastest, and easiest way to compare two tables in SQL Server: UNION相关推荐

  1. 转载-SQL Server各种导入导出数据方式的比较

    注:本文转载自 http://blog.csdn.net/nokiaguy/article/details/4684822 当我们建立一个数据库时,并且想将分散在各处的不同类型的数据库分类汇总在这个新 ...

  2. [转载] sql server 2000系统表解释

    sql server 2000系统表解释 汇总了几个比较有用的系统表,内容摘自联机帮助 sysobjects --------------- 在数据库内创建的每个对象(约束.默认值.日志.规则.存储过 ...

  3. [转载]SQL Server行列转换实现

    一.Pivot和UnPivot介绍 1.Pivot介绍 PIVOT用于将列值旋转为列名(即行转列),在SQL Server 2000可以用聚合函数配合CASE语句实现 PIVOT的一般语法是:PIVO ...

  4. [转载]在SQL Server数据库之间进行数据导入导出,OPENDATASOURCE

    需要在c盘下先建立一个data.txt文件,然后在文件的第一行写上你要导出的列,不如说要导出id和name这两列,就在第一行写上 id,name 然后保存,使用下列SQL就可以了,你如果要保持原有的I ...

  5. 转载:有关SQL server connection Keep Alive 的FAQ(3)

    转载:http://blogs.msdn.com/b/apgcdsd/archive/2012/06/07/sql-server-connection-keep-alive-faq-3.aspx 这个 ...

  6. SQL Server中的锁类型及用法(转载)

    一. 为什么要引入锁 多个用户同时对数据库的并发操作时会带来以下数据不一致的问题: 丢失更新  A,B两个用户读同一数据并进行修改,其中一个用户的修改结果破坏了另一个修改的结果,比如订票系统 脏读  ...

  7. SQL Server 表分区注意事项(转载)

    在园子里看到 听风吹雨 关于SQL Server 表分区注意事项 ,总结的太好了.备忘,方便以后查询! http://www.cnblogs.com/gaizai/archive/2011/05/31 ...

  8. SQL Server 2005 的版本和组件[转载]

    可以在生产环境中使用所有版本的 SQL Server 2005,但 SQL Server 2005 Developer Edition 和 SQL Server 2005 Evaluation Edi ...

  9. SQL Server 2005 镜像构建说明(转载)

    一. 镜像简介 1. 简介 数据库镜像是将数据库事务处理从一个SQL Server数据库移动到不同SQL Server环境中的另一个SQL Server数据库中.镜像不能直接访问;它只用在错误恢复的情 ...

最新文章

  1. R语言ggplot2包和ggtext包在可视化图像中的指定位置添加文本框(横向文本框、竖向文本框)
  2. 不定位成一个连接者,家装公司进军智能装饰的所有姿势都是错的
  3. Qt IFW框架简介
  4. Tomcat10 下载和配置 Linux 环境
  5. 【VRP】基于matlab蚁群算法求解多中心的车辆路径规划问题【含Matlab源码 111期】
  6. python 文件 解析ddl_BKM ? 35期 — Python解析ANSYS文件
  7. .har 文件解析工具
  8. exoplay切换全屏_如何使用rotation-degrees手动旋转(rotate)exoplayer2播放器
  9. Matlab 官网培训 - 大型项目-风力发电机数据模型构建-Catching the Wind
  10. cachecloud部署详细过程
  11. APP开发者如何选择适合的广告联盟或聚合广告平台
  12. 2021DASCTF实战精英夏令营暨DASCTF July X CBCTF 4th -- WP [pwn]
  13. 【计算分段函数】输入整数x和a,计算并输出分段函数的值(保留2位小数)。
  14. 【腾讯QQ官方正式版下载】基于Internet的即时通信(IM)软件
  15. 人脸检测(十五)--改进版VJ人脸检测(LBP特征,VISAPP2017)
  16. 妈蛋,终于在TQ2440上点亮一个led了。。。
  17. python bokeh模块_Python 绘图 – Bokeh 初探
  18. MySql基础篇---002 SQL之SELECT使用篇: 基本的SELECT语句,运算符,排序与分页,多表查询,单行函数,聚合函数,子查询
  19. npm报错Failed at the node-sass@4.14.1 postinstall script
  20. android 自动 轮播图,Android-自定义View实现轮播图

热门文章

  1. 《Python从小白到大牛》第7章 运算符
  2. QQ登录的那些坑(如何开发qq登陆功能)
  3. Redis键值相关命令
  4. MySQL模拟:线上误update的恢复
  5. Oracle数据库用户角色、表空间创建、删除命令
  6. 通过FxCop来验证.NET编码规范
  7. 华为3com交换路由命令详解
  8. 【Python-ML】SKlearn库层次聚类凝聚AgglomerativeClustering模型
  9. 【正一专栏】评《我的前半生》——我们需要怎样的价值观
  10. ubuntu下部署eclipse集成hadoop\android\web\GCC开发环境小记