Partilhar via


INICIAR TRANSAÇÃO

Aplica-se a:sim marcado Databricks SQL

Inicia uma nova transação interativa que agrupa múltiplas instruções SQL numa única unidade de trabalho que pode ser comprometida ou revertida.

Como alternativa às transações interativas, pode definir transações não interativas usando a BEGIN ATOMIC ... END; sintaxe. Veja a declaração do composto ATOMIC.

Sintaxe

BEGIN { TRANSACTION | WORK }

Parâmetros

Esta afirmação não tem parâmetros.

Notes

  • Se uma transação interativa já estiver ativa, a BEGIN TRANSACTION execução novamente resulta num TRANSACTION_NOT_SUPPORTED.NESTED_TRANSACTION erro. Transações interativas não suportam aninhamento.
  • BEGIN TRANSACTION e BEGIN WORK são alternativas sintáticas equivalentes.

Exemplos

Os exemplos seguintes demonstram padrões comuns de transação interativa.

Transação básica entre tabelas

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

Leia as suas próprias escritas

Executa 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 rollback

Executa 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 mudanças não confirmadas

Neste exemplo, as alterações dentro de uma transação não são visíveis para outras sessões até que a transação seja confirmada. Executa 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):

-- Now commit the transaction
COMMIT TRANSACTION;

Sessão 2 (após o commit):

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

Visibilidade das alterações simultâneas

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

Sessão 1 (iniciar uma transação e ler 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 (continuado, releia 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;

Isto garante leituras consistentes ao longo da transação, independentemente das modificações simultâneas.