共用方式為


開始交易

適用於:勾選「是」 Databricks SQL

開始新的交互式交易,將多個 SQL 語句分組為一個可提交或回滾的工作單元。

作為互動式交易的替代方案,你可以用語 BEGIN ATOMIC ... END; 法來定義非互動式交易。 參見 原子化合物陳述

語法

BEGIN { TRANSACTION | WORK }

參數

此陳述沒有參數。

Notes

  • 如果互動式交易已經啟動,再次執行 BEGIN TRANSACTION 會產生 TRANSACTION_NOT_SUPPORTED。NESTED_TRANSACTION 錯誤。 互動式交易不支援嵌套。
  • BEGIN TRANSACTIONBEGIN WORK 是等價的語法替代方案。

Examples

以下範例展示了常見的互動交易模式。

基本的交叉表格交易

逐一執行每個語句。

BEGIN TRANSACTION;
-- Insert a new record
INSERT INTO my_table VALUES (1, 'test');
-- Update records in another table
UPDATE another_table
SET value = 'updated'
WHERE id = 5;
-- Commit all changes in both tables atomically
COMMIT TRANSACTION;

自讀自寫

逐一執行每個語句。

BEGIN TRANSACTION;
-- Insert new data
INSERT INTO customers VALUES (101, 'New Customer');
-- Query can see the inserted data within the same transaction
SELECT * FROM customers WHERE id = 101;
-- Returns the newly inserted row even though it's not yet committed
-- Update the newly inserted data
UPDATE customers SET name = 'Updated Customer Name' WHERE id = 101;
-- Query sees the updated value
SELECT name FROM customers WHERE id = 101;
-- Returns 'Updated Customer Name'
-- Commit makes changes visible to other transactions
COMMIT TRANSACTION;

回滾交易

逐一執行每個語句。

BEGIN TRANSACTION;
-- Attempt an insert operation
INSERT INTO my_table VALUES (1, 'incorrect-value');
-- After discovering the mistake, rollback the transaction
-- (no changes are actually made to the tables)
ROLLBACK TRANSACTION;

未承諾變更的可見性

在此範例中,只有在交易提交後,交易內部的變更才會對其他會話可見。 逐一執行每個語句。

第一場:

BEGIN TRANSACTION;
-- Insert new data
INSERT INTO products VALUES (999, 'New Product', 29.99);
-- At this point, Session 2 cannot see this data
-- You can see your own changes
SELECT * FROM products WHERE id = 999;
-- Returns the new product

第二場(同時進行):

-- This query does not see the uncommitted data from Session 1
SELECT * FROM products WHERE id = 999;
-- Returns no rows

第一場(續):

-- Now commit the transaction
COMMIT TRANSACTION;

階段 2(提交後):

-- Now the query can see the committed data
SELECT * FROM products WHERE id = 999;
-- Returns the new product

同時變更的可見性

在此範例中,交易外的同時變更對交易本身是不可見的。 Azure Databricks 在首次存取時擷取每個資料表的一致快照,之後所有對該資料表的讀取都使用這個快照(可重複讀取)。 逐一執行每個語句。

第一階段 (開始交易並閱讀表格):

BEGIN TRANSACTION;
-- Read the table; captures a snapshot of orders at this point
SELECT COUNT(*) FROM orders;
-- Returns: 1

第二場次 (並行場次會增加一列):

INSERT INTO orders VALUES (2, 'Product B', 75.00);
COMMIT;

第一場會議 (續,請重讀表格):

-- Still reads from the original snapshot; the new row is not visible
SELECT COUNT(*) FROM orders;
-- Returns: 1 (unchanged, even though Session 2 committed a new row)
COMMIT;

這確保了整個交易過程中的讀取一致性,無論是否有同時修改。