OracleDB entry 4: delete all the contents of the specified schema

background

    As mentioned earlier, a schema is a collection of database objects owned by ORACLE database users. Project objects include structures such as tables, views, sequences, stored procedures, synonyms, indexes, clusters, and database links . Usually, the program object includes all the content created by the application in the database. Specifically, an ORACLE user corresponds to a schema.

detailed steps

Create a SQL script (drop_schema.sql) file with the following content

set define on
set serveroutput on
connect / as sysdba

define schema = &1

-- Kill Session connecting to the schemas to be dropped
Declare
    Cursor c_session Is
    SELECT s.sid, s.serial# FROM gv$session s
      JOIN gv$process p ON p.addr = s.paddr  AND p.inst_id = s.inst_id
      WHERE s.type != 'BACKGROUND' AND s.username = '&schema';
Begin
    For r_session In c_session Loop
         Execute Immediate 'ALTER SYSTEM KILL SESSION '''||r_session.sid||','||r_session.serial#||'''';
    End Loop;
End;
/

-- Drop schemas
Drop User &schema Cascade;

set define off
exit

Add execute permission for SQL script

chmod +x drop_schema.sql 

Execute SQL script

$sqlplus /nolog 
SQL> @drop_schema.sql

result

                 

Source code explanation

  • set define on/off

Open/substitute variable function.

  • set serveroutput on

Display server output information in the window.

  • declare … begin… end

The anonymous block that starts with the declare or begin keyword is called an anonymous block. It needs to be compiled every time it is used, and cannot be stored in the database and cannot be called by other PL/SQL. The begin...end statement block is used here to disconnect all links of the specified schema (user). If you do not disconnect the link, drop user XXX Cascade directly and an error may be reported.

  • "/" backslash

The slash is to let the server execute the sql script written earlier. If it is an ordinary select statement, a semicolon can be executed. But if it is a stored procedure, it cannot be executed immediately if it encounters a semicolon. At this time, it needs to be executed through a slash (/).

  • drop user XXX Cascade

Delete all content under the user (schema)

Expand

 Of course, the main command of the script is  drop user XXX Cascade , because we have user dba permissions. Therefore, you can also use the method of restarting the database to disconnect all users' links (shutdown immediate, startup open)

Guess you like

Origin blog.csdn.net/zhaogang1993/article/details/89502277