问题
I'm trying to code a statement that checks if a table exist and if it does to truncate/delete it. If it doesn't exist, to print the message 'This table does not exist!'
This is what I've come up so far but doesn't seem to work.
BEGIN
TRUNCATE TABLE PPA_P6_2018;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE = -942 THEN
DBMS_OUTPUT.put_line('This table does not exist!');
ELSE
RAISE;
DBMS_OUTPUT.put_line('This table has been delted!');
END IF;
END;
回答1:
DECLARE
v_count NUMBER;
v_table_name VARCHAR2 (100) := 'YOURTABLE';
v_sqlstr VARCHAR2 (1000);
BEGIN
SELECT COUNT ( * )
INTO v_count
FROM user_tables
WHERE table_name = v_table_name;
IF v_count > 0
THEN
v_sqlstr := 'DELETE FROM ' || v_table_name;
EXECUTE IMMEDIATE v_sqlstr;
DBMS_OUTPUT.put_line (
'TABLE ' || v_table_name || ' HAS BEEN DELETED!');
ELSE
DBMS_OUTPUT.put_line ('TABLE ' || v_table_name || ' DOES NOT EXIST!');
END IF;
END;
回答2:
Create a custom exception to catch when the table does not exist and then only catch that single exception (rather than catching all of them with OTHERS
) and then use EXECUTE IMMEDIATE
to truncate/drop the table:
DECLARE
table_name VARCHAR2(30) := 'PPA_P6_2018';
table_not_exists EXCEPTION;
PRAGMA EXCEPTION_INIT( table_not_exists, -942 );
BEGIN
EXECUTE IMMEDIATE 'TRUNCATE TABLE ' || table_name;
EXECUTE IMMEDIATE 'DROP TABLE ' || table_name;
DBMS_OUTPUT.put_line('This table has been deleted!');
EXCEPTION
WHEN table_not_exists THEN
DBMS_OUTPUT.put_line('This table does not exist!');
END;
/
db<>fiddle
回答3:
TRUNCATE TABLE
is DDL so cannot be run directly within PL/SQL. You need to use EXECUTE IMMEDIATE
:
BEGIN
EXECUTE IMMEDIATE 'TRUNCATE TABLE PPA_P6_2018';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE = -942 THEN
DBMS_OUTPUT.put_line('This table does not exist!');
ELSE
RAISE;
DBMS_OUTPUT.put_line('This table has been delted!');
END IF;
END;
Note: You will never see the message 'This table has been delted!' since the RAISE before it throws you out of the block! And if you got an error, the table hasn't been deleted anyway!
来源:https://stackoverflow.com/questions/58658067/sql-check-if-table-exist-and-truncate