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

2024-01-07

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

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);

有没有什么合适的方法来实现这个功能?


您确实不应该在 PL/SQL 中执行此操作,在运行时创建的表将表明您的数据模型中存在缺陷。如果您确实确信必须这样做,那么请进行调查临时表 http://docs.oracle.com/cd/E11882_01/server.112/e25494/tables003.htm#ADMIN11633第一的。就我个人而言,我会重新评估是否有必要。

你似乎要去EAFP 与 LBYL 相对 http://oranlooney.com/lbyl-vs-eafp/方法,在一些答案中描述了这个问题 https://stackoverflow.com/questions/1799128/oracle-if-table-exists。我认为这是不必要的。表是一个相当静态的野兽,您可以使用系统视图用户表 http://docs.oracle.com/cd/E11882_01/server.112/e25513/statviews_5480.htm#REFRN26286在删除它之前确定它是否存在。

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;
/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Oracle pl/sql 中创建或替换表 的相关文章

随机推荐