0

Can you help me rectify this block of code plz?

`CREATE OR REPLACE FUNCTION TABLE_EXISTS(name VARCHAR(50))
RETURNS BOOLEAN
AS
BEGIN
    DECLARE counttable INTEGER;

    SELECT COUNT(1) INTO counttable FROM USER_TABLES WHERE TABLE_NAME=name;

    if counttable=0 then
    return false
    else
    return true
    end if;
END;
/
IF (TABLE_EXISTS("LEADS_DELETED")) then
DROP TABLE LEADS_DELETED;
end if;
/
CREATE GLOBAL TEMPORARY TABLE LEADS_DELETED
(
    ID NUMBER(19),
    PRIMARY KEY (ID)
) ON COMMIT DELETE ROWS`
1
  • What is your problem? What doesn't work? Commented Aug 19, 2011 at 8:05

2 Answers 2

2

You can use a construct like this when you want to create or recreate a table (try to drop and catch the ORA-00942 exception that gets thrown when the object doesn't exist):

DECLARE
   table_does_not_exist exception;
   pragma exception_init(table_does_not_exist, -942);
BEGIN
   EXECUTE IMMEDIATE 'DROP TABLE LEADS_DELETED';
EXCEPTION
   WHEN table_does_not_exist THEN
      NULL;
END;
/

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

Comments

2

You have double quotes aroung your table name "LEADS_DELETED" should be 'LEADS_DELETED'.

I'd also wrap the table_name in your query with UPPER(table_name) too.

You also need to put the DROP TABLE command inside an EXECUTE IMMEDIATE wrapper.

You declare your variable in the wrog place too, it needs to be declared before the BEGIN clause.

CREATE OR REPLACE 
FUNCTION TABLE_EXISTS(name VARCHAR(50)) 
  RETURNS BOOLEAN 
AS 
   counttable INTEGER; 
BEGIN 
   SELECT COUNT(1) 
     INTO counttable 
     FROM USER_TABLES 
    WHERE TABLE_NAME=UPPER(name);      

    if counttable=0 
    then     
       return false     
    else     
       return true     
    end if; 
END; 
/ 

-- I suggest you use a bind variable instead of the literal table name.
IF TABLE_EXISTS('LEADS_DELETED') 
THEN
  EXECUTE IMMEDIATE 'DROP TABLE LEADS_DELETED';
END IF;
/ 

-- Could be
IF table_exists(v_table_name)
THEN
   EXECUTE IMMEDIATE 'DROP TABLE :tablename'
   USING v_table_name;
END IF;

2 Comments

hi the drop logic is where i call the function. it is a query which i used to demonstrate why i need the function. so there is no need for execute immediate i think
thanks for your effort ollie! maybe later we can work on getting this function to work :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.