背景
准备测试对象
--为了方便验证,我直接在同实例下新建了两个测试库 --准备同步的库以及表 CREATE DATABASE test_db1; --源库 GO USE test_db1; CREATE TABLE test_table --需同步的源表 ( id INT IDENTITY(1, 1), name NVARCHAR(20), location NVARCHAR(10) ); GO CREATE DATABASE test_db2; --目标库 GO USE test_db2; CREATE TABLE test_table --需同步的目标表 ( id INT IDENTITY(1, 1), name NVARCHAR(20), location NVARCHAR(10) ); GO
--开启xp_cmdshell EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;
测试场景情况
USE test_db1; --源库 INSERT INTO dbo.test_table --源表 ( name, location ) VALUES ( N'1', -- name - nvarchar(20) N'2' -- location - nvarchar(10) );
EXEC master..xp_cmdshell '"C:\Program Files\Microsoft SQL Server\140\COM\tablediff.exe" -sourceserver [DESKTOP-0LI9ARF] -sourcedatabase test_db1 -sourcetable test_table -destinationserver [DESKTOP-0LI9ARF] -destinationdatabase test_db2 -destinationtable test_table -f D:\4_9\Diff';
USE test_db2; --目标库 INSERT INTO dbo.test_table --目标表 ( name, location ) VALUES ( N'23', -- name - nvarchar(20) N'232' -- location - nvarchar(10) ); INSERT INTO dbo.test_table --目标表 ( name, location ) VALUES ( N'232', -- name - nvarchar(20) N'2233' -- location - nvarchar(10) );
EXEC master..xp_cmdshell '"C:\Program Files\Microsoft SQL Server\140\COM\tablediff.exe" -sourceserver [DESKTOP-0LI9ARF] -sourcedatabase test_db1 -sourcetable test_table -destinationserver [DESKTOP-0LI9ARF] -destinationdatabase test_db2 -destinationtable test_table -f D:\4_9\Diff';
USE test_db1; CREATE TABLE test_table2 --需同步的源表2 ( name NVARCHAR(20), location NVARCHAR(10) ); GO USE test_db2; CREATE TABLE test_table2 --需同步的目标表2 ( name NVARCHAR(20), location NVARCHAR(10) ); GO
USE test_db1; --目标库 INSERT INTO dbo.test_table2 --目标表 ( name, location ) VALUES ( N'23', -- name - nvarchar(20) N'232' -- location - nvarchar(10) ); INSERT INTO dbo.test_table2 --目标表 ( name, location ) VALUES ( N'232', -- name - nvarchar(20) N'2233' -- location - nvarchar(10) );
EXEC master..xp_cmdshell '"C:\Program Files\Microsoft SQL Server\140\COM\tablediff.exe" -sourceserver [DESKTOP-0LI9ARF] -sourcedatabase test_db1 -sourcetable test_table2 -destinationserver [DESKTOP-0LI9ARF] -destinationdatabase test_db2 -destinationtable test_table2 -f D:\4_9\Diff1';
EXEC master..xp_cmdshell '"C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\sqlcmd.exe" -S DESKTOP-0LI9ARF -d test_db2 -i D:\4_9\Diff.sql -o D:\4_9\error1.txt';
结论
- 从上述测试来看基本验证此方案是可行,不过使用到生产环境就要做充分测试验证,如磁盘的IO到时是否会有瓶颈,网络情况等;
- 注意tablediff的限制,满足比对的前提是要有【primary key】或【identity】或【ROWGUID 】,如没有就需手工增加一个,注意使用-strict 选项 会有一些限制注意查看官方文档;
- 注意开启xp_cmdshell会有一定的安全风险;
- 注意在sqlcmd 中字母区分大小写且有不同的含义,详情查看官方文档;