检查表是否存在功能

时间:2011-08-19 07:53:22

标签: sql oracle sql-function

你能帮我纠正这段代码吗?

`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`

2 个答案:

答案 0 :(得分:2)

当您想要创建或重新创建表时,可以使用这样的结构(尝试删除并捕获在对象不存在时抛出的ORA-00942异常):

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 ...

答案 1 :(得分:2)

您的表格名称“LEADS_DELETED”应为“LEADS_DELETED”。

我也会使用UPPER(table_name)将table_name包装在你的查询中。

您还需要将DROP TABLE命令放在EXECUTE IMMEDIATE包装器中。

你也要在wrog地方声明你的变量,它需要在BEGIN子句之前声明。

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;