Emre D.
Emre D.

Reputation: 579

How can i update multiple databases at the same time in SQL Server?

I have 7 databases. 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?

Upvotes: 2

Views: 8968

Answers (4)

Almazini
Almazini

Reputation: 1873

You can add all your servers/databases to one group in Registered servers pane (SQL Management Studio(2016): Ctrl + Alt + G to show it). 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.

Upvotes: 2

Dmitry Kolchev
Dmitry Kolchev

Reputation: 2216

Why you need the same tables with the same data in different databases. IMHO you need redesign your application and database. Possible solutions:

  1. Common schema and data move to single database
  2. If you nevertheless need data duplication you can change data in single database, and use transactional replication for data delivery to other databases.
  3. You need use cross-database transactions

-

 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

Upvotes: -1

Zaynul Abadin Tuhin
Zaynul Abadin Tuhin

Reputation: 31993

I think trigger can help you below is sudo code and use roll back transaction if fails

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

Upvotes: 0

AswinRajaram
AswinRajaram

Reputation: 1622

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!

Upvotes: 0

Related Questions