标签:
做数据迁移或者复制时,有时需要验证目标表和源表之间的数据差异。下面我们就介绍几种验证数据差异的方法:
1.两个表连接查询,对比每一列的值
Declare @vSQL varchar(max) Declare @vCols varchar(max) Create Table vTable1 (id int, StudentID int, Dept varchar(10),BookID int) Create Table vTable2 (id int, StudentID int, Dept varchar(10),BookID int) Insert into vTable1 Select 1,123,‘CS‘,465 Union All Select 2,123,‘CS‘,345 Union All Select 3,223,‘TE‘,190 Insert into vTable2 Select 1,123,‘CS‘,465 Union All Select 2,223,‘TE‘,345 Union All Select 3,223,‘TE‘,190 -- Get the column names from schema with case statements to get 0 or 1 as result -- Now, this will depend upon the columns of your actual tables -- Data approach Select @vCols = Stuff((Select ‘,case when a.‘ + [name] + ‘ = b.‘ + [name] + ‘ then Cast(b.‘ + [name]+‘ as varchar(10)) else cast(b.‘ + [name] + ‘ as varchar(max)) + ‘‘(old)‘‘ + ‘‘ ‘‘ + Cast(a.‘ + [name] + ‘ as varchar(10)) + ‘‘(new)‘‘ end as ‘ + [name] from sys.columns where Object_id = Object_id(‘vTable1‘) for XML Path(‘‘)),1,1,‘‘) -- Concatenate the @vCols with main sql Set @vSQL = ‘ Select a.id,‘ + @vCols + ‘ From vTable1 a Inner Join vTable2 b on b.ID = a.ID ‘ Print @vSQL Exec (@vSQL) --Flag approach Select @vCols = Stuff((Select ‘,case when a.‘ + [name] + ‘ = b.‘ + [name] + ‘ then 1 else 0 end as ‘ + [name] from sys.columns where Object_id = Object_id(‘vTable1‘) for XML Path(‘‘)),1,1,‘‘) Set @vSQL = ‘ Select a.id,‘ + @vCols + ‘ From vTable1 a Inner Join vTable2 b on b.ID = a.ID ‘ Print @vSQL Exec (@vSQL) Drop table vTable1 Drop table vTable2
2.对比两个表的总行数
Select count(1) from table_a
select count(1) from table_b
如果表上有时间字段,用这个方式去对比也是OK的,这种方法只能看总行数是否一致。
3. 用微软提供的tablediff 工具
先对比两个数据一样的表
truncate table FunctionMenu_t
insert into FunctionMenu_t
select * from dbo.FunctionMenu
再对比数据不一样的表
update top(1) FunctionMenu_t set Id =‘aaaa‘
对比结果给出了两个表之间的不同。
4. 用复制工具验证数据一致性
---------------------------------------------
Tablediff参数
tablediff [ -? ] | { -sourceserver source_server_name[\instance_name] -sourcedatabase source_database -sourcetable source_table_name [ -sourceschema source_schema_name ] [ -sourcepassword source_password ] [ -sourceuser source_login ] [ -sourcelocked ] -destinationserver destination_server_name[\instance_name] -destinationdatabase subscription_database -destinationtable destination_table [ -destinationschema destination_schema_name ] [ -destinationpassword destination_password ] [ -destinationuser destination_login ] [ -destinationlocked ] [ -b large_object_bytes ] [ -bf number_of_statements ] [ -c ] [ -dt ] [ -et table_name ] [ -f [ file_name ] ] [ -o output_file_name ] [ -q ] [ -rc number_of_retries ] [ -ri retry_interval ] [ -strict ] [ -t connection_timeouts ] }
-c 对比列
-b 大数据类型要对比的字节数,任何大于此值的大数据类型列都不会对比
-o 输出文件的完整路径和名称。
-q 只进行行数和架构的比较。
标签:
原文地址:http://www.cnblogs.com/alexwu/p/4872464.html