I am taking a database class and at the beginning of the lab section of the class we usually have to drop all the tables in the database created previously. I wanted to be able to run a script that does this dynamically, but cannot seem to get it to work. Here is the code I have so far.
declare tname string(50);
cursor ctable is select table_name from user_tables;
begin
open ctable;
LOOP
FETCH ctable into tname;
if tname != '' then
execute immediate 'drop table ' || tname;
END if;
EXIT WHEN ctable%NOTFOUND;
END LOOP;
close ctable;
end;
If someone could point me in the right direction as to what I am doing wrong that would great. Thanks.
Oracle’s
VARCHAR2treats empty strings asNULL.So
is the same as
which will return
NULLinstead ofTRUEsince it is not defined.You can check for
NULLbytname IS NOT NULL.table_nameis mandatory inuser_tablesthough, so there is no need for this check.Two more things:
%NOTFOUNDimmediately after fetchinguser_tables.table_name%TYPE)So your code could look like that:
You could also use an implicit cursor for better readability: