I would like to perform a DROP VIEW IF EXISTS...
command on an Oracle DB as it can be done on a MySQL database. How can this be achieved?
An alternate method:
DECLARE
dne_942 EXCEPTION;
PRAGMA EXCEPTION_INIT(dne_942, -942);
BEGIN
EXECUTE IMMEDIATE 'DROP VIEW my_view';
EXCEPTION
WHEN dne_942 THEN
NULL; -- if it doesn't exist, do nothing .. no error, nothing .. ignore.
END;
/
This has the added benefit of not needing to query the data dictionary .. just try to fire the drop .. and if it doesn't exist .. that's fine .. no real issue.
-
Looks a bit scary/obscure but I do agree that it's good that there is no duplication of the view name. Good to know of other options! – Daniel Gray Aug 19 '19 at 17:49
-
1@WernfriedDomscheit And that's no different than any other solution ... you add whatever additional error handling you need. – Ditto Aug 19 '19 at 19:50
If you're using sqlplus (I use it for a lot of batch processes) you can just ignore the error:
WHENEVER SQLERROR CONTINUE;
DROP VIEW my_view;
WHENEVER SQLERROR EXIT 1;
After you ignore the possible error from dropping the view, you might want to turn it back to the regular behavior (exit on error). The 1
is optional, in case you want to raise the errorlevel.
There is no way to do it in a single command, but it can be achieved with a small PL/SQL block as follows:
DECLARE cnt NUMBER;
BEGIN
SELECT COUNT(*) INTO cnt FROM user_views WHERE view_name = 'MY_VIEW';
IF cnt <> 0 THEN
EXECUTE IMMEDIATE 'DROP VIEW my_view';
END IF;
END;
/
IF EXISTS
sort of behavior. – Daniel Gray Aug 19 '19 at 17:42