有人可以指导我这个查询有什么问题吗?在 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;
Run Code Online (Sandbox Code Playgroud)
我得到输出 - 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;
Run Code Online (Sandbox Code Playgroud)
正如 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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20279 次 |
| 最近记录: |