I remember from university that:
By Default, doing Insert, Delete and update on 2 or more data sources can't be participant under a transaction
This sounds like it was taken out of context, because as it's currently written, without any other details, it's an incorrect statement.
You can apply multiple DML statements (INSERT
, UPDATE
, DELETE
) to multiple data sources under the same transaction. In SQL Server, such transaction just needs to be explicitly defined around all of the DML statements that you want to partake within the same transaction. For example:
BEGIN TRANSACTION
UPDATE TableA
SET Column1 = 0;
INSERT INTO TableB (Column2)
VALUES (123);
ROLLBACK;
In the above example, two different statements are affecting two different tables, and both get rolled back at the end of the transaction.
Without explicitly specifying a transaction around them, then each statement is executed atomically as its own transaction, individually, per statement instead.
I can't create a script that an Insert perform on Northwind database and another Insert doesn't perform on TestDB but rollback can't delete inserted row on Northwind database.
Sorry, I don't understand what you're trying to say here. Can you please provide an example with dbfiddle.uk perhaps?
Question 1) Does transactions manage under a Instance or manage under a Database? I mean multiple database can that exist in a given instance can participant in one transaction?
Yes, multiple databases can partake within the same single transaction. A transaction can be defined to be as granular as you want, or as macroscopic as you want, and include any number of data sources, whether within the same database or not.
Question 2) If TestDB exists in another instance of SQL Server (For example MyServer2), Is it possible that include it in one transaction with current instance (For example MyServer1).
Yes, this is called a distributed transaction.
Could you please show me a sample code?
Sure, here's some code from an example in the aforementioned docs on distributed transactions:
USE AdventureWorks2022;
GO
BEGIN DISTRIBUTED TRANSACTION;
-- Delete candidate from local instance.
DELETE AdventureWorks2022.HumanResources.JobCandidate
WHERE JobCandidateID = 13;
-- Delete candidate from remote instance.
DELETE RemoteServer.AdventureWorks2022.HumanResources.JobCandidate
WHERE JobCandidateID = 13;
COMMIT TRANSACTION;
In this example, a deletion happens on the local copy of the table JobCandidate
and also on the remote copy of it from another SQL Server instance, all within the same transaction. If an error occurred and a rollback happened, both changes would be undone as well.
Please note, in order to use distributed transactions, the Microsoft Distributed Transaction Coordinator (MS DTC) needs to be enabled and properly configured on the remote server.