T-SQL 的表级差异和同步过程
我对用于将表(或者可能是表的子集)与另一个类似表中的数据同步的 T-SQL 源代码感兴趣。这两个表可以包含任何变量,例如我可以有
base table source table
========== ============
id val id val
---------- ------------
0 1 0 3
1 2 1 2
2 3 3 4
或
base table source table
=================== ==================
key val1 val2 key val1 val2
------------------- ------------------
A 1 0 A 1 1
B 2 1 C 2 2
C 3 3 E 4 0
或 任何两个包含具有相似名称的相似列的表。我希望能够
- 检查这两个表是否有 匹配列:源表具有与基表完全相同的列,并且数据类型匹配,
- 使基表与源表之间存在差异,
- 执行必要的更新、删除和插入以更改源表中的数据 与源表相对应的基表
- 可选地将差异限制为基表的子集,
最好使用存储过程。有没有人为此编写过存储过程,或者您能指出一个来源吗?
I'm interested in T-SQL source code for synchronizing a table (or perhaps a subset of it) with data from another similar table. The two tables could contain any variables, for example I could have
base table source table
========== ============
id val id val
---------- ------------
0 1 0 3
1 2 1 2
2 3 3 4
or
base table source table
=================== ==================
key val1 val2 key val1 val2
------------------- ------------------
A 1 0 A 1 1
B 2 1 C 2 2
C 3 3 E 4 0
or any two tables containing similar columns with similar names. I'd like to be able to
- check that the two tables have
matching columns: the source table has exactly the same columns as the base table and the datatypes match - make a diff from the base table to the source table
- do the necessary updates, deletes and inserts to change the data in the
base table to correspond the source table - optionally limit the diff to a subset of the base table,
preferrably with a stored procedure. Has anyone written a stored proc for this or could you point to a source?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
SQL Server 2008 采用了新的合并语句。它非常灵活,虽然写起来有点复杂。
例如,以下查询将同步
@base
和@source
表。它仅限于@base
的子集,其中id <> 2:
SQL Server 2008 features the new merge statement. It's very flexible, if a bit complex to write out.
As an example, the following query would synchronize the
@base
and@source
tables. It's limited to a subset of@base
whereid <> 2
:有趣的问题。
您可以从 EXCEPT - INTERSECT
http://msdn.microsoft.com/en 开始-us/library/ms188055.aspx
这是现成的解决方案,可能会帮助您
http ://www.sqlservercentral.com/scripts/Miscellaneous/30596/
Interesting question.
you could start from EXCEPT - INTERSECT
http://msdn.microsoft.com/en-us/library/ms188055.aspx
Here is readymade solution, may help you
http://www.sqlservercentral.com/scripts/Miscellaneous/30596/
不确定它对您的具体情况是否有任何用处,但这种操作通常可以使用外部工具(SQL Workbench diff、SQL Compare 等)相对轻松地完成。
它甚至可以编写脚本,只是可能无法从 T-SQL 过程调用。
Not sure if it's of any use to your specific situation, but this kind of operation is usually and relatively easily done using external tools (SQL Workbench diff, SQL Compare etc.).
It can even be scripted, just probably not invokable from a T-SQL procedure.