kul*_*rim 3 sql database oracle plsql
我需要一个创建表的脚本,或者如果它已经存在则删除它,并在重新创建表时.经过一些研究,我发现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);
Run Code Online (Sandbox Code Playgroud)
有没有正确的方法来实现这个功能?
你真的不应该在PL/SQL中这样做,在运行时创建的表将表明你的数据模型存在缺陷.如果你真的相信你绝对必须这样做,那么先调查临时表.就个人而言,我会重新评估是否有必要.
你似乎是在寻求EAFP而不是LBYL方法,这个问题在一些答案中有所描述.我认为这是不必要的.表是一个相当静态的野兽,您可以使用系统视图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;
/
Run Code Online (Sandbox Code Playgroud)
使用全局临时表似乎是更好的选择.但是,如果您坚持在运行时删除并重新添加表,则可以查询其中一个_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(...)';
Run Code Online (Sandbox Code Playgroud)
分享和享受.