Create table if it doesn't exist [message #205142] |
Thu, 23 November 2006 08:04 |
alexh2084
Messages: 7 Registered: November 2006 Location: Brasov
|
Junior Member |
|
|
Hi,
I'm new to Oracle and i have a big problem: i have an sql script file written for MySql and i have to rewrite it for Oracle
The file contains only sql statement like create table, select, update and delete and doesn't contain procedures.
i have to delete and create a table but only if it exists... in mysql the instructions are:
drop table if exists user;
.............
create temporary table if not exists tmp_pwd (pwd varchar(28));
.............
i haven't found in Oracle the equivalent of the "if exists" statement. I have searched the net and i saw that after if you cannot use the "exists" clause and that "if" can be used only after "where"
The other solutions i have found used Pl/SQL but i cannot use them. I have to use only sql statements that will be saved in a file and the executed using Ant
Any suggestions appreciated.
Thanks in advance.
|
|
|
Re: Create table if it doesn't exist [message #205155 is a reply to message #205142] |
Thu, 23 November 2006 09:30 |
ThomasG
Messages: 3211 Registered: April 2005 Location: Heilbronn, Germany
|
Senior Member |
|
|
Hi,
I'm not aware of a way to do it without PL/SQL.
Can't you put a SQL like this in the ANT script ?
BEGIN
EXECUTE IMMEDIATE ('DROP TABLE test');
EXECUTE IMMEDIATE ('CREATE TABLE test(x number(1))');
Dbms_Output.put_line('CHECK -> : Table recreated');
EXCEPTION
WHEN OTHERS THEN
Dbms_Output.put_line('CHECK -> : Table does not exist');
END;
/
That way it tries to drop / create the table, but if the table does not exist it jumps to the exception handler.
In SQL Plus it works :
SQL> -- enable output
SQL> SET SERVEROUTPUT ON SIZE 1000000
SQL>
SQL> -- create table
SQL> CREATE TABLE test (x NUMBER(1));
Table created.
SQL>
SQL> -- try script with table present
SQL> BEGIN
2 EXECUTE IMMEDIATE ('DROP TABLE test');
3 EXECUTE IMMEDIATE ('CREATE TABLE test(x number(1))');
4 Dbms_Output.put_line('CHECK -> : Table recreated');
5 EXCEPTION
6 WHEN OTHERS THEN
7 Dbms_Output.put_line('CHECK -> : Table does not exist');
8 END;
9 /
CHECK -> : Table recreated
PL/SQL procedure successfully completed.
SQL> -- drop table
SQL> drop TABLE test;
Table dropped.
SQL>
SQL> -- try script without table present
SQL> BEGIN
2 EXECUTE IMMEDIATE ('DROP TABLE test');
3 EXECUTE IMMEDIATE ('CREATE TABLE test(x number(1))');
4 Dbms_Output.put_line('CHECK -> : Table recreated');
5 EXCEPTION
6 WHEN OTHERS THEN
7 Dbms_Output.put_line('CHECK -> : Table does not exist');
8 END;
9 /
CHECK -> : Table does not exist
PL/SQL procedure successfully completed.
SQL>
|
|
|
|
|
|