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.

5
  • Write the queries in a file (script) and then run the script: techonthenet.com/oracle/questions/script.php Commented Jun 2, 2011 at 9:28
  • 1
    I did it in TOAD IDE. WE can run multiple queries at a time by pressing F5 I think(Done long back) Commented Jun 2, 2011 at 9:28
  • Also see this: download.oracle.com/docs/cd/B10501_01/server.920/a90842/ch6.htm Commented Jun 2, 2011 at 9: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? Commented Jun 2, 2011 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. Commented Jun 5, 2011 at 8:51

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

don't forget about execute immediate for DDL statements here
Thanks for pointing that out. I learned something new today! :)
Create a procedure just to run it once at a life, why not run it directly?
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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.