[英]How can i update multiple databases at the same time in SQL Server?
I have 7 databases.我有 7 个数据库。 Databases have same tables.数据库具有相同的表。 I want to update all of them at the same time when i edit row or add new row.我想在编辑行或添加新行时同时更新所有这些。 If one of transactions doesn't work , It will not be updated.如果其中一项交易不起作用,则不会更新。
How can i update?我怎样才能更新?
You can add all your servers/databases to one group in Registered servers pane (SQL Management Studio(2016): Ctrl + Alt + G to show it).您可以将所有服务器/数据库添加到已注册服务器窗格中的一组(SQL Management Studio(2016):Ctrl + Alt + G 以显示它)。 Under local serves Groups.在本地服务组下。
Then press right button on a new group and select "New Query".然后在新组上按右键并选择“新建查询”。
When you execute query it will run on all servers in selected group.当您执行查询时,它将在选定组中的所有服务器上运行。
Update or Modify a single table and use the same table across different databases.更新或修改单个表并在不同的数据库中使用相同的表。 That is better than trying to maintain data consistency across 7 tables in 7 databases!这比试图在 7 个数据库中的 7 个表之间保持数据一致性更好!
I think trigger can help you below is sudo code and use roll back transaction if fails我认为下面的触发器可以帮助您 sudo 代码并在失败时使用回滚事务
USE Test;--Test is one db
GO
CREATE TRIGGER afterInsert ON table AFTER INSERT
AS
BEGIN
IF @@rowcount = 0 RETURN;
UPDATE Test2.[schema_name(default schema is dbo)].Clients --here test2 is another db
SET col = col +1 -- or whatever it should be
FROM Test2.[schema_name(default schema is dbo)].Clients c
INNER JOIN inserted i ON ([your join condition])
END;
GO
Why you need the same tables with the same data in different databases.为什么在不同的数据库中需要具有相同数据的相同表。 IMHO you need redesign your application and database.恕我直言,您需要重新设计您的应用程序和数据库。 Possible solutions:可能的解决方案:
- ——
begin try
begin transaction;
update db1..table1 set field1 = value1, field2 = value2 where key = @key;
update db2..table1 set field1 = value1, field2 = value2 where key = @key;
...
update dbN..table1 set field1 = value1, field2 = value2 where key = @key;
commit transaction;
end try
begin catch
SELECT
ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage;
if @@trancount > 0
rollback transaction;
end catch
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.