在Oracle pl / sql中创建或替换表

时间:2013-05-19 12:35:01

标签: sql database oracle plsql

我需要一个创建表的脚本,或者如果它已经存在则删除它,并在重新创建表时。经过一些研究,我发现pl / sql中的CREATE OR REPLACE TABLE不存在。所以我想出了这个脚本:

DECLARE
   does_not_exist   EXCEPTION;
   PRAGMA EXCEPTION_INIT (does_not_exist, -942);
BEGIN
   EXECUTE IMMEDIATE 'DROP TABLE foobar';
EXCEPTION
   WHEN does_not_exist
   THEN
      NULL;
END;
/ 

CREATE TABLE foobar (c1 INT);

有没有正确的方法来实现此功能?

2 个答案:

答案 0 :(得分:9)

你真的不应该在PL / SQL中这样做,在运行时创建的表将指示数据模型中的缺陷。如果你真的相信你绝对必须这样做,那么首先调查temporary tables。就个人而言,我会重新评估是否有必要。

您似乎采用了EAFP as opposed to LBYL方法,在this question的几个答案中对此进行了描述。我认为这是不必要的。表是一个相当静态的野兽,您可以使用系统视图USER_TABLES来确定它是否存在,然后再删除它。

declare

   l_ct number;

begin

   -- Determine if the table exists.
   select count(*) into l_ct
     from user_tables
    where table_name = 'THE_TABLE';

   -- Drop the table if it exists.
   if l_ct = 1 then
      execute immediate 'drop table the_table';
   end if;

   -- Create the new table it either didn-t exist or
   -- has been dropped so any exceptions are exceptional.
   execute immediate 'create table the_table ( ... )';

end;
/

答案 1 :(得分:5)

使用全局temporary table似乎是更好的选择。但是,如果您坚持在运行时删除并重新添加表,则可以查询其中一个_TABLES视图(即USER_TABLES,DBA_TABLES,ALL_TABLES)以确定该表是否存在,如果存在则删除它,然后创建它:

SELECT COUNT(*)
  INTO nCount
  FROM USER_TABLES
  WHERE TABLE_NAME = 'FOOBAR';

IF nCount <> 0 THEN
  EXECUTE IMMEDIATE 'DROP TABLE FOOBAR';
END IF;

EXECUTE IMMEDIATE 'CREATE TABLE FOOBAR(...)';

分享并享受。