Compartilhar via


INICIAR TRANSAÇÃO

Aplica-se a:marcado como 'sim' Databricks SQL

Inicia uma nova transação interativa que agrupa várias instruções SQL em uma única unidade de trabalho que pode ser confirmada ou revertida.

Como alternativa a transações interativas, você pode definir transações não interativas usando a BEGIN ATOMIC ... END; sintaxe. Consulte a declaração composta ATOMIC.

Sintaxe

BEGIN { TRANSACTION | WORK }

Parâmetros

Essa instrução não tem parâmetros.

Observações

  • Se uma transação interativa já estiver ativa, executar BEGIN TRANSACTION novamente resultará em um erro TRANSACTION_NOT_SUPPORTED.NESTED_TRANSACTION. Transações interativas não dão suporte ao aninhamento.
  • BEGIN TRANSACTION e BEGIN WORK são alternativas de sintaxe equivalentes.

Exemplos

Os exemplos a seguir demonstram padrões de transação interativos comuns.

Transação de tabela cruzada básica

Execute cada instrução separadamente.

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;

Ler suas próprias gravações

Execute cada instrução separadamente.

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;

Transação com reversão

Execute cada instrução separadamente.

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;

Visibilidade de alterações não confirmadas

Neste exemplo, as alterações em uma transação não são visíveis para outras sessões até que a transação seja confirmada. Execute cada instrução separadamente.

Sessão 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

Sessão 2 (simultânea):

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

Sessão 1 (continuação):

-- Now commit the transaction
COMMIT TRANSACTION;

Sessão 2 (após a confirmação):

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

Visibilidade de alterações simultâneas

Neste exemplo, as alterações simultâneas feitas fora da transação não são visíveis para a transação. O Azure Databricks captura um instantâneo consistente de cada tabela no primeiro acesso e todas as leituras subsequentes dessa tabela usam esse instantâneo (leitura repetível). Execute cada instrução separadamente.

Sessão 1 (inicie uma transação e leia a tabela):

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

Sessão 2 (sessão simultânea adiciona uma linha):

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

Sessão 1 (continuada, leia novamente a tabela):

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

Isso garante leituras consistentes em toda a transação, independentemente de modificações simultâneas.