通过


开始事务

适用于:勾选“是” Databricks SQL

开始一个新的交互式事务,该事务将多个 SQL 语句分组到可以提交或回滚的单个工作单元中。

作为交互式事务的替代方法,可以使用语法定义非交互式事务 BEGIN ATOMIC ... END; 。 请参阅 ATOMIC 复合语句

Syntax

BEGIN { TRANSACTION | WORK }

参数

此语句没有参数。

备注

  • 如果交互式事务已处于活动状态,则再次执行 BEGIN TRANSACTION 将导致 TRANSACTION_NOT_SUPPORTED。NESTED_TRANSACTION 错误。 交互式事务不支持嵌套。
  • BEGIN TRANSACTIONBEGIN WORK 等效的语法替代方法。

示例

以下示例演示了常见的交互式事务模式。

基本跨表事务

单独运行每个语句。

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;

未提交的更改的可见性

在此示例中,在事务提交前,事务中的更改对其他会话不可见。 单独运行每个语句。

会话 1:

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

会话 2 (并发):

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

会话 1 (继续):

-- 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 在首次访问时捕获每个表的一致快照,并且该表的所有后续读取都使用此快照(可重复读取)。 单独运行每个语句。

会话 1 (启动事务并读取表):

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

会话 2 (并发会话添加行):

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

会话 1 (继续,重新读取表):

-- 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;

这保证在事务执行过程中始终的一致读取,无论是否存在并发修改。