Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use transaction with oracle SQL?

I am trying to use transaction blocks on a SQL-Console with an Oracle DB. I'm used to use transaxction blocks in PostgreSQL like

BEGIN;
<simple sql statement>
END;

but in oracle it seems that this is not possible. I'm always getting "ORA-00900" errors and I don't know how to fix that. If I just use SQL-Statements like

<simple sql statement>
COMMIT;

it works. But isn't there some tag to define the start of a transaction? I tried

START TRANSACTION;
<simple sql statement>
COMMIT;

But it still throws an ORA-00900. My operating system is windows, I am using IntelliJ IDEA and a Oracle 11g DB.

like image 214
Vortilion Avatar asked Feb 03 '16 13:02

Vortilion


People also ask

How do transactions work in Oracle?

A transaction is a logical, atomic unit of work that contains one or more SQL statements. A transaction groups SQL statements so that they are either all committed, which means they are applied to the database, or all rolled back, which means they are undone from the database.

How do I do a transaction in SQL?

Example of COMMIT Transaction The following steps illustrate to create a transaction: Start the transaction using the BEGIN TRANSACTION command. Write the SQL statements and divide them based on our needs. Use the COMMIT statement to complete the transaction and save the changes permanently.

How do I start and end a transaction in Oracle?

How to Begin and End Transactions. You begin a transaction with the first executable SQL statement (other than CONNECT) in your program. When one transaction ends, the next executable SQL statement automatically begins another transaction. Thus, every executable statement is part of a transaction.

How do I start a transaction in PL SQL?

The transaction begins with the first SQL statement issued after the previous transaction, or with the first SQL statement issued after connecting to the database. The transaction ends with the COMMIT or ROLLBACK statement.


Video Answer


1 Answers

You can have an implicit transaction block by issuing one SQL statement as in

<simple sql statement>
Commit;

For anonymous blocks or PL/SQL procedures/functions/packages more options are available that you may have seen in Postgres.

If you have several statements that must all succeed or all fall (an atomic transaction then, from the documentation, you can do:

DECLARE
   <variable declaration>
BEGIN
   <simple sql statement>
   <simple sql statement>
   <simple sql statement>
   SAVEPOINT do_insert;
   <sql insert statement>
EXCEPTION
   WHEN DUP_VAL_ON_INDEX THEN
      ROLLBACK TO do_insert;
      DBMS_OUTPUT.PUT_LINE('Insert has been rolled back');
END;
--and commit outside the transaction
like image 163
kevinskio Avatar answered Oct 03 '22 23:10

kevinskio