|
|
Re: How to detect if a table exists [message #144622 is a reply to message #144620] |
Thu, 27 October 2005 07:57   |
 |
Maaher
Messages: 7065 Registered: December 2001
|
Senior Member |
|
|
I'm no fan of table creation in PL/SQL. If it's a temporary table, look for alternatives, like PL/SQL tables, global temporary tables,...
But here are a couple of ways:
SQL> DESC employees
Name Null? Type
----------------------------------------- -------- -----------------
EMPLOYEE_ID NOT NULL NUMBER(6)
FIRST_NAME VARCHAR2(20)
LAST_NAME NOT NULL VARCHAR2(25)
EMAIL NOT NULL VARCHAR2(25)
PHONE_NUMBER VARCHAR2(20)
HIRE_DATE NOT NULL DATE
JOB_ID NOT NULL VARCHAR2(10)
SALARY NUMBER(8,2)
COMMISSION_PCT NUMBER(2,2)
MANAGER_ID NUMBER(6)
DEPARTMENT_ID NUMBER(4)
SQL> begin
2 execute immediate 'CREATE TABLE EMPLOYEES(ID NUMBER)';
3 end;
4 /
begin
*
ERROR at line 1:
ORA-00955: name is already used by an existing object
ORA-06512: at line 2
SQL> DECLARE
2 E_TAB_EXISTS EXCEPTION;
3 PRAGMA EXCEPTION_INIT(E_TAB_EXISTS,-955);
4 BEGIN
5 execute immediate 'CREATE TABLE EMPLOYEES(ID NUMBER)';
6 EXCEPTION
7 WHEN E_TAB_EXISTS THEN
8 dbms_output.put_line('Table already exists');
9 end;
10 /
Table already exists
PL/SQL procedure successfully completed.
SQL> ed
Wrote file afiedt.buf
1 DECLARE
2 CURSOR c_tab
3 IS
4 SELECT table_name
5 FROM user_tables
6 WHERE table_name = 'EMPLOYEES';
7 v_tab VARCHAR2(30);
8 BEGIN
9 OPEN c_tab;
10 FETCH c_tab INTO v_tab;
11 IF c_tab%NOTFOUND THEN
12 execute immediate 'CREATE TABLE EMPLOYEES(ID NUMBER)';
13 ELSE
14 dbms_output.put_line('Table already exists, not created.');
15 END IF;
16 CLOSE c_tab;
17* END;
SQL> /
Table already exists, not created.
PL/SQL procedure successfully completed.
SQL>
MHE
|
|
|
|
Re: How to detect if a table exists [message #144655 is a reply to message #144620] |
Thu, 27 October 2005 10:05  |
ducasio
Messages: 38 Registered: November 2003
|
Member |
|
|
In the solution of Maaher I would prefer to use the "TAB" table or "USER_OBJECTS" view; in this way you can avoid the failing of table creation that has the same name of a synonym or another object type for che user schema.
bye,
ducasio
|
|
|