有人可以指导我这个查询有什么问题吗?在 SQL Server 中,我们只检查表的 Object_ID 是否存在以删除它并重新创建它。我是 Oracle 的新手并写了这个查询:
declare Table_exists INTEGER;
BEGIN
Select count(*) into Table_exists from sys.all_tables where table_name='TABLENAME1';
EXCEPTION
WHEN NO_DATA_FOUND
THEN
Table_Exists :=0;
if(table_exists)=1
Then
Execute Immediate 'Drop Table TABLENAME1;'
'Create Table TABLENAME1;';
DBMS_OUTPUT.PUT_LINE('Table Dropped and Re-Created!');
Else
Execute Immediate 'Create Table TABLENAME1;';
DBMS_OUTPUT.PUT_LINE('New Table Created!');
END IF;
END;
我得到输出 - ANONYMOUS BLOCK COMPLETED,但未创建表。该表先前已存在,因此我将其删除以检查 PL/SQL 是否实际创建了该表,但没有。这里有什么问题?我错过了什么?请指导。
最佳答案
EXCEPTION 子句持续到下一个 END 而不仅仅是下一个语句。如果您想在捕获异常后继续,您需要添加额外的 BEGIN/END:
declare
Table_exists INTEGER;
BEGIN
BEGIN
Select count(*) into Table_exists from sys.all_tables where table_name='TABLENAME1';
EXCEPTION
WHEN NO_DATA_FOUND THEN
Table_Exists :=0;
END;
if(table_exists)=1 Then
Execute Immediate 'Drop Table TABLENAME1;'
Execute Immediate 'Create Table TABLENAME1;';
DBMS_OUTPUT.PUT_LINE('Table Dropped and Re-Created!');
Else
Execute Immediate 'Create Table TABLENAME1;';
DBMS_OUTPUT.PUT_LINE('New Table Created!');
END IF;
END;
正如 Gordon 所指出的,在这种情况下实际上并不需要 EXCEPTION 子句,因为
count(*)
将始终返回一行。所以以下就足够了:declare
Table_exists INTEGER;
BEGIN
Select count(*) into Table_exists from sys.all_tables where table_name='TABLENAME1';
if(table_exists)=1 Then
Execute Immediate 'Drop Table TABLENAME1;'
Execute Immediate 'Create Table TABLENAME1;';
DBMS_OUTPUT.PUT_LINE('Table Dropped and Re-Created!');
Else
Execute Immediate 'Create Table TABLENAME1;';
DBMS_OUTPUT.PUT_LINE('New Table Created!');
END IF;
END;
关于sql - Oracle SQL - 如果存在,删除表并创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31585746/