12

I have a create table query, an update query ,and then drop table query. I need to run these three queries in one shot. What is the best way to do this?

Example
1st Query: Create table A.
2nd Query: Update value in table A
3rd Query: Drop table A.

Instead of running these three queries one by one, I want to run them in on go either by PLSQL or some other way. Please help.

Joel Beckham
  • 18,254
  • 3
  • 35
  • 58
Vikram Singh
  • 121
  • 1
  • 1
  • 3
  • Write the queries in a file (script) and then run the script: http://www.techonthenet.com/oracle/questions/script.php – ypercubeᵀᴹ Jun 02 '11 at 09:28
  • 1
    I did it in TOAD IDE. WE can run multiple queries at a time by pressing F5 I think(Done long back) – Max Jun 02 '11 at 09:28
  • Also see this: http://download.oracle.com/docs/cd/B10501_01/server.920/a90842/ch6.htm – ypercubeᵀᴹ Jun 02 '11 at 09:30
  • 2
    Sometimes you don't need the (temporary) staging table at all e.g. can use a CTE instead. But isn't the net result of running all three (create A, update A, drop A) exactly nothing? – onedaywhen Jun 02 '11 at 11:01
  • Creating and dropping tables in a single Unit Of Work is a code smell. It might be necessary in some other databases, but it is not necessary in Oracle: there are always better ways, depending on precisely what it is you need to do. – APC Jun 05 '11 at 08:51

3 Answers3

10

Put the 3 queries following each other separated by a semi-colon:

SELECT * 
FROM table_to_be_selected; 
DROP TABLE the table_to_be_dropped; 
TRUNCATE TABLE table_to_be_truncated;

You can concatenate these queries in a string and execute that string.

adius
  • 13,685
  • 7
  • 45
  • 46
DaMainBoss
  • 2,035
  • 1
  • 19
  • 26
7

Why not create a PROCEDURE?

E.g.

CREATE OR REPLACE PROCEDURE foo
IS
BEGIN
  -- The create sentence goes here. For example:
  -- EXECUTE IMMEDIATE
  -- 'CREATE TABLE bar (...)';

  -- The update sentence goes here
  -- EXECUTE IMMEDIATE
  -- 'UPDATE bar SET ...';

  -- The drop/delete sentence goes here.
  -- EXECUTE IMMEDIATE
  -- 'DROP TABLE bar;'
END;

You can test it with:

SET serveroutput ON;
exec foo;

The PROCEDURE is stored on the database, so you can use it later on.

Hope this helps.

whirlwin
  • 16,044
  • 17
  • 67
  • 98
5

Simply put three queries one after the other in a .sql file, with semi-colons after each statement, then execute it as a script (either on a SQL*Plus prompt using @scriptname.sql or in TOAD/SQL Developer [or equivalent] using its script execution function).

Datajam
  • 4,141
  • 2
  • 23
  • 25