DBA Procedures

DBA Procedures: Resources

1. Creating project databases
    a) Connect as oracle/internal or system/manager.
    b) CREATE DATABASE Test
        
DATAFILE 'C:\Oracle\Oradata\TEST\System01.dbf ' 40M
         LOGFILE 'C:\Oracle\Oradata\TEST\Redo01.log' SIZE 150K,
                          'C:\Oracle\Oradata\TEST\Redo02.log' SIZE 150K
        ARCHIVELOG;

    
    

# Startup Command 
CONNECT AS INTERNAL/ORACLE
STARTUP FORCE

------------------------------------------------------
STARTUP
STARTUP PFILE=$ORACLE_HOME/dbs/initdb01.ora
ALTER DATABASE db01 MOUNT;
ALTER DATABASE OPEN
_____________________
# Opening database in read-only mode.
STARTUP MOUNT
ALTER DATABASE OPEN READ ONLY;
_____________________

2.. Managing DB Objects (Creating a new tablespace)
    Note: * Each database is logically divided into one or more tablespaces
    * One or more datafiles are explicitly created for each tablespace to physically store the data 
        of all logical structures in a tablespace.
    * The combined size of a tablespace's datafiles is the total storage capacity of the tablespace
       (SYSTEM tablespace has 2 MB storage capacity while USERS tablespace has 4 MB). 
    * The combined storage capacity of a database's tablespaces is the total storage capacity of 
       the database (6 MB). 
    a) Connect as system/manager
    b) CREATE TABLESPACE MY_TEMP
         DATAFILE 'C:\Oracle\Oradata\TEST\Temp02.dbf ' SIZE 200K
         DEFAULT STORAGE (PCTINCREASE 0);

          or

        CREATE TABLESPACE MY_DATA
        DATAFILE 'C:\Oracle\Oradata\TEST\Data01.dbf ' SIZE 200K
        DEFAULT STORAGE (INITIAL 10K
                                              NEXT 10K
                                              PCTINCREASE 0);

  
c) Result: Tablespace created.
   d) Query the data dictionary to verify your tablespaces have been created.
         SQL>
connect internal/oracle
                   # (Needed whenever you are starting or shutting down the database)
        SQL>
startup force 
                  # (Bounces the database..shutdown..startup)


To look at the Data Dictionary:
       
SELECT * FROM DBA_TABLESPACES;
or to look at specific fields in data dictionary:
SELECT OWNER, TABLE_NAME, TABLESPACE_NAME FROM DBA_TABLES;

   e) A tablespace can be online (accessible) or offline (not accessible). A tablespace is normally
       online so that users can access the information within the tablespace. However, sometimes a
       tablespace is taken offline to make a portion of the database unavailable while allowing normal
       access to the remainder of the database. This makes many administrative tasks easier to
       perform. 

3. Create a new table.
    CREATE TABLE MY_TABLE
     (fname varchar2(10),
      lname varchar2(10),
      phone number (10))
   TABLESPACE MY_DATA;       

4. Insert data into new table. Connect as system manager.
   a)
CONNECT SYSTEM/MANAGER
  
b) INSERT INTO MY_TABLE VALUES('Terry', 'Stough', '2056789459');
 
Note: A rollback segment may be needed.
   c) CREATE ROLLBACK SEGMENT RBS11
          STORAGE(OPTIMAL 100K)
          TABLESPACE MY_RBS;
  
Result: Rollback segment created
  Note: Query the data dictionary to ensure the new that the new rollback segment 
            has a STATUS of ONLINE.
 
d) SELECT SEGMENT_NAME, OWNER, STATUS
      FROM DBA_ROLLBACK_SEGS;
 
Result: RGS11 (rollback segment) should say ONLINE.
    (Now insert data into new table (b))
 e) Note: Modify your parameter file (init.ora) to ensure the instance acquires your rollback 
     segments at startup.
    # This is the init.ora file.
    # If using private rollback segments, place lines of he following
    # form in each of your instance-specific init.ora files:
    rollback_segments = ( RBS11 )

  5. Create a unique index on the my_table lname column. Name the index my_index1 
       and place it in the my_index tablespace.
     a) CONNECT AS SYSTEM/MANAGER

     b) CREATE UNIQUE INDEX MY_INDEX1
         ON My_Table(lname)
         TABLESPACE MY_INDEX;

         Result: Index created.

         or 
        (Create a non-unique composite index on the my_table lname and fname columns. Name the index my_index2):

         CREATE INDEX MY_INDEX2
         ON My_Table(fname, lname)
         TABLESPACE MY_INDEX;
         
Result: Index created.
      
      c) Query the data dictionary and verify your index segments have been created.
           SELECT INDEX_NAME
           FROM USER
_INDEXES
           WHERE INDEX_NAME LIKE 'MY_INDEX%';

           
Result: INDEX_NAME is MY_INDEX1 and MY_INDEX2

6. Manage Database Users: Find out what the DEFAULT and TEMPORARY tablespaces are for the user you log on as:
     a)
CONNECT TRAIN/TRAIN
     b)
SELECT DEFAULT_TABLESPACE, TEMPORARY_TABLESPACE
         FROM USER_USERS;
     
    Result: DEFAULT_TABLESPACE is USERS and 
                    TEMPORARY_TABLESPACE is TEMP.

     c) CONNECT SYSTEM/MANAGER
     d) SELECT DEFAULT_TABLESPACE, TEMPORARY_TABLESPACE
         FROM USER_USERS;
        
Result: DEFAULT_TABLESPACE is TOOLS and 
                    TEMPORARY_TABLESPACE is TEMP.
   
     e) Query DBA_USERS. Does any user have SYSTEM as their DEFAULT or 
         TEMPORARY tablespace?

        
SELECT USERNAME, DEFAULT_TABLESPACE, TEMPORARY_TABLESPACE
         FROM DBA_USERS
         WHERE DEFAULT_TABLESPACE = 'SYSTEM'
            OR TEMPORARY_TABLESPACE = 'SYSTEM';

 
7. Query the V$SESSION to determine the SERIAL# and SID of your session. List the 
      command that would be used to terminate your session.

    SELECT 'ALTER SYSTEM KILL SESSION ' || "" ||
      SID || ',' || Serial# || "" || ';' COMMAND
      FROM V$Session
      WHERE UserName = USER;
   
Results:
     COMMAND: ALTER SYSTEM KILL SESSION '7,27';
   
         
8. Create User Account and grant permissions:
   
a) CONNECT SYSTEM/MANAGER
    b) CREATE USER TEST IDENTIFIED BY TEST
        GRANT CREATE SESSION TO TEST;

Note: GRANT CONNECT, RESOURCE to TEST 
# should work also where TEST is the USER..

     Result: The User Test with the password of Test was created.
                       Test was given the 'CREATE SESSION' privilege.
Note: GRANT CONNECT, RESOURCE to STGEORGED WITH ADMIN OPTION;
          # This gives STGEORGED admin privileges to now grant same privileges to others;

   c) To see what Oracle roles the user has been given.
       SELECT username, granted_role, admin_option
       FROM user_role_privs;
      
also
       SELECT * FROM session_privs


    d) Query DBA_USERS and DBA_TS_QUOTAS to view TEST's tablespace and quota
         information.
         SELECT DEFAULT_TABLESPACE, TEMPORARY_TABLESPACE
         FROM DBA_USERS
         WHERE USERNAME = ' TEST ' ;
       
Result: DEFAULT_TABLESPACE and TEMPORARY_TABLESPACE are both
                   SYSTEM.

        SELECT TABLESPACE_NAME, MAX_BYTES
        FROM DBA_TS_QUOTAS
        WHERE USERNAME = ' TEST ' ;
       
Result: TABLE_SPACE is SYSTEM and MAX_BYTES is -1.

    e) Since the System tablespace is reserved for dictionary objects; remove Test's quota from the 
         from the system tablespace and provide a quota for the my_data tablespace. Also specify
          my_data as Test's default tablespace and my_temp as the temporary tablespace.

        ALTER USER TEST
         DEFAULT TABLESPACE MY_DATA
         TEMPORARY TABLESPACE MY_TEMP
         QUOTA 10M ON MY_DATA
         QUOTA   0M on SYSTEM;

          Result: User alterered.


  9. Giving and revoking access to projects for users
10. Establishing back up procedures for all databases.
11. To change user password from TEACHER/SUBJECT to TEACHER/CLASS:
       ALTER USER TEACHER IDENTIFIED BY CLASS;
     


TIPS:
1) In SQLPlus type:
HELP INDEX
# this will give you a list of the commands.
HELP COMMAND_NAME will give you more specifics.
2) Database export within Perl
3)
Using the import utility. The following script shows how you can run sql scripts with sqlplus from within a Perl program (you will want to scroll down towards the bottom of the file)
4) Getting Oracle to do calculations:
From SqlPlus type:
SELECT (3 + 3) FROM DUAL;
or SELECT 3 + 3 FROM DUAL;
5) From NewsGroups:
When you recieve the formula in a string format, the only options is to
create a stored PL/SQL function
and work with dynamic SQL or Ref Cursors.  I used Ref Cursors for a problem
that is quite similar to
yours.  Hopelfully this example PL/SQL function makes it clear

CREATE OR REPLACE FUNCTION CALCULATE_FORMULA(formula in varchar2) return
number
AS
    TYPE dynamic_cursor_type IS REF CURSOR;
    dynamic_cursor dynamic_cursor_type;
    cursor_source VARCHAR2(200);
    result number := 0;
BEGIN
    cursor_source := 'select '||formula||' from dual';
    OPEN dynamic_cursor FOR cursor_source;
    FETCH dynamic_cursor INTO result;
    CLOSE dynamic_cursor;
    return result;
EXCEPTION
    when others
    then
        raise_application_error(-20110, 'CALCULATION ERROR. PLEASE CHECK
YOUR FORMULA!', TRUE);
END;

# Note: formula is where you put math to be done

6)  Working with Functions:
SQL> CREATE OR REPLACE FUNCTION hello_func (
        name_  IN VARCHAR2) RETURN VARCHAR2
     IS
     BEGIN
        RETURN 'Hello ' || name_;
     END hello_func;
     /
SQL> Function Created.
SQL> select hello_func('David') "Hello String" from dual;

Hello String
-------------------------
Hello David




7) # Spooling and turning off headers type:

set echo off
set heading off
set verify off
set feedback off
set serveroutput on
spool D.LOG

SELECT '=== Exec of D.SQL ' || TO_CHAR(SYSDATE, 'DD.MM.YYYY') || ' ===' FROM
DUAL
/

ACCEPT inp PROMPT 'Input something? (Y/N)'


prompt   === End of Script D.SQL===

SPOOL OFF

--------------------------------------------------------------
Look at Later:
DECLARE
    -- Declare the OLE objects
    MyApplication OLE2.OBJ_TYPE;
    MyDocuments OLE2.OBJ_TYPE;
    MyDocument OLE2.OBJ_TYPE;

    -- Declare handle to the OLE argument list
    args OLE2.LIST_TYPE;
    var varchar2(100);
 
 BEGIN

  -- Create the Word.Application object and make Word visible
  -- by setting the 'Visible' property to true, by default it is
invisible.
  MyApplication:=OLE2.CREATE_OBJ('Word.Application'); 
 
  OLE2.SET_PROPERTY(MyApplication, 'Visible', 'True'); -- Comment this
line to hide the application.

  -- get a handle on Documents collection
  MyDocuments:=OLE2.GET_OBJ_PROPERTY(MyApplication, 'Documents');
 
  -- Open a new document 
  MyDocument :=OLE2.INVOKE_OBJ(MyDocuments,'Add');
  OLE2.DESTROY_ARGLIST(args);

message('Adding Document Variable');

  -- Create a document variable MyVar and populate with the value 12
  args:=OLE2.CREATE_ARGLIST;
  OLE2.ADD_ARG(args, 'MyVar');
  OLE2.ADD_ARG(args, '12');
  OLE2.INVOKE(MyDocument,'Variables.Add',args);
  OLE2.DESTROY_ARGLIST(args);

message('Reading Document Variable');

  -- Read the document variable and display on Forms message line 
  args:=OLE2.CREATE_ARGLIST;
  OLE2.ADD_ARG(args, 'MyVar');
  var:=OLE2.INVOKE_CHAR(MyDocument,'Variables',args);
message(var);
  OLE2.DESTROY_ARGLIST(args);

  -- Release the OLE objects
  OLE2.INVOKE(MyDocument,'Close'); 
  OLE2.RELEASE_OBJ(MyDocument);
  OLE2.RELEASE_OBJ(MyDocuments);
  OLE2.RELEASE_OBJ(MyApplication);

exception 
  when others then
  
     message(sqlerrm||sqlcode);
     OLE2.DESTROY_ARGLIST(args);
     OLE2.INVOKE(MyDocument,'Close'); 
    -- Release the OLE objects
     OLE2.RELEASE_OBJ(MyDocument);
     OLE2.RELEASE_OBJ(MyDocuments);
     OLE2.RELEASE_OBJ(MyApplication);
END;

--------------------------------------------
Look at Later:
Build a table into the Oracle database, and called "MYTABLE1" something like this. 

ID
(type: number) User Name(type: varchar2) Phone(type: varchar2) Email(type: varchar2) 
100  Colin Tong  999-999-8888  [email protected]  
111  John White  888-888-8888  [email protected]  
101  Don Wod  416-333-3344  [email protected]  

Access and retrieve data
     1) Instantiate OO4O Object, OraSession and interface OraDatabase for 
        connecting to ORACLE.
     First of all, create the OraSession Object by using CreateObject, then create the 
     OraDatabase Object by opening a connection to Oracle, as shown below. 

<%
Set OraSession = CreateObject("OracleInProcServer.XOraSession")
Set OraDatabase = OraSession.OpenDatabase("", _
     "username/password", Cint(0))
%>


     The "username" and "password" are your relational database's user name and 
    password. 
     2) Create an OraDynaset Object to execute SQL statement. You may use either 
     CreateDynaset or DbCreateDynaset to create the recordset. 


<%
'execute SQL
Set OraDynaset = OraDatabase.DbCreateDynaset( _
    "select * from mytable1", cint(0))
%>

     3) Retrieve data and remove created object 
<%
  Do While(OraDynaset.EOF = FALSE) 
    Response.write(OraDynaset.Fields("ID"))
    Response.write(OraDynaset.Fields("UserName"))
    ... others ... 
    ... ...
    OraDynaset.MoveNext
  Loop
  'remove OraSession
  Set OraSession = Nothing
%>

Edit data record
    We are going to use the methods of OraDynaset to implement the editing data purpose.

     1) Create OraDynaset object with SQL Statement 

<%
'Create the OraDynaset Object for ID= fID record. 
Set OraDynaset = OraDatabase.CreateDynaset(_
    "select * from MYTABLE1 where ID= "& fID, cint(0))
%>

     The fID is the value of the ID field that you want to update or insert.

    2) Execute OraDynaset for updating or adding 

<%
    'update the field of the record(ID=fID) using Edit method.
    'or use the AddNew to insert a new record
    OraDynaset.Edit
    OraDynaset.Fields("Phone").Value = fPhone
    OraDynaset.Update

    ' remove the created session
    Set OraSession = Nothing
%>

Delete data record.
Some of you might already know how to delete record(s) from Oracle DB 
using OraDynaset if you really understand the methods that we used
 (Edit, Update and AddNew) at above sections. Actually, we simply use the method 
Delete of OraDynaset for deleting. 
 
<% 
   'Delete all records that with above condition.
   OraDynaset.Delete
%>

Sample codes for search and update data records from Oracle8i

   1) Searching 
<%
 '*************************************************************
 'RetrieveRecProc.asp -Retrieve records using OO4O in ASP
 'Original Author: Colin Tong 
 'Modified Date: 9/26/2001
 'Note: You are free to use this code, however, please keep 
 'the original author name.
 '*************************************************************
%>
<%
'Declare variables as OLE Objects.
 Dim OraSession 
 Dim OraDatabase
 Dim OraDynaset
'Create the OraSession Object.
 Set OraSession = CreateObject("OracleInProcServer.XOraSession")
'Create the OraDatabase Object by opening a connection to Oracle.
'Be sure your own username and password to access your Oracle db
 Set OraDatabase = OraSession.OpenDatabase("", "user/password", _
     Cint(0))
   
'Create the OraDynaset Object to execute SQL statement
 Set OraDynaset = OraDatabase.DbCreateDynaset(_
     "select * from mytable1", cint(0))
%>

Retrieve All Records in MYTABLE1 Table ( in Oracle) Using oo4o

<% Do While(OraDynaset.EOF = FALSE) Response.Write("") OraDynaset.MoveNext Loop 'remove OraSession Set OraSession = Nothing %>
") Response.write(OraDynaset.Fields("ID")) Response.Write("") Response.write(OraDynaset.Fields("UserName")) Response.Write("") Response.write(OraDynaset.Fields("Phone")) Response.Write("") Response.write(OraDynaset.Fields("Email")) Response.Write("
Hosted by www.Geocities.ws

2) Updating <% '************************************************************** 'UpdateRecProc.asp -Update a record using OO4O in ASP 'Original Author: Colin Tong 'Modified Date: 9/26/2001 'Note: You are free to use this code, however please keep 'the original author name. '************************************************************** %> <% 'Declare variables as OLE Objects. Dim OraSession Dim OraDatabase Dim OraDynaset 'get field values from submitted form fID = request.form("ID") fUserName = request.form("UserName") fPhone = request.form("Phone") fEmail = request.form("Email") 'Create the OraSession Object Set OraSession = CreateObject("OracleInProcServer.XOraSession") 'Create the OraDatabase Object by opening a connection to Oracle Set OraDatabase = OraSession.OpenDatabase("", "user/password", _ Cint(0)) 'Create the OraDynaset Object for ID= fID record Set OraDynaset = OraDatabase.CreateDynaset(_ "select * from MYTABLE1 where ID= "& fID, cint(0)) 'update the field of the record(ID=fID) using Edit method Do While(OraDynaset.EOF = FALSE) OraDynaset.Edit OraDynaset.Fields("UserName").Value = fUserName OraDynaset.Fields("Phone").Value = fPhone OraDynaset.Fields("Email").Value = fEmail OraDynaset.Update OraDynaset.MoveNext Loop %>

Update A Record in MYTABLE1 Table (Oracle) Using oo4o

The record (ID=<%=fID%>) has been updated successfully!
<% 'remove OraSession Set OraSession = Nothing %> ------------------------------------------------- Forms Developer and Reports Developer Built-in Package [ole_odref60.pdf] (pg44) /* ** Start Excel, perform some operations on the ** spreadsheet, then close the application. */ DECLARE AppID PLS_INTEGER; BEGIN AppID := DDE.App_Begin('c:\excel\excel.exe emp.xls', DDE.App_Mode_Normal); ... DDE.App_End(AppID); END; ------------------------------------ DDE.App_Focus example /* ** Start Excel, then activate the application window */ DECLARE AppID PLS_INTEGER; BEGIN AppID := DDE.App_Begin('c:\excel\excel.exe', DDE.App_Mode_Maximized); DDE.App_Focus(AppID); ----------------------------- DDE.Execute example /* ** Initiate Excel, then perform a recalculation */ DECLARE ConvID PLS_INTEGER; BEGIN ConvID := DDE.Initiate('EXCEL', 'abc.xls'); DDE.Execute(ConvID, '[calculate.now()]', 1000); END; -------------------------------------------- DDE.Poke example /* ** Open a DDE Conversation with MS Excel on topic ** abc.xls and end data "foo" to cell at row 2, ** column 2 */ DECLARE ConvID PLS_INTEGER; BEGIN ConvID = DDE.Initiate('EXCEL', 'abc.xls'); DDE.Poke(ConvID, 'R2C2', 'foo', DDE.CF_TEXT, 1000); END; ---------------------------------------------- DDE.Request example /* ** Open a DDE Conversation with MS Excel for Windows on ** topic abc.xls then request data from 6 cells ** between row 2, column 2 and row 3, column 4 */ DECLARE ConvID PLS_INTEGER; Buffer VARCHAR2(80); BEGIN ConvID := DDE.Initiate('EXCEL', 'abc.xls'); DDE.Request (ConvID, 'R2C2:R3C4', Buffer, DDE.Cf_Text, 1000); END; ------------------------------------------------------- DDE.Terminate example /* ** Open a DDE Conversation with MS Excel on topic ** abc.xls perform some operations, then terminate ** the conversation */ DECLARE ConvID PLS_INTEGER; BEGIN ConvID := DDE.Initiate('EXCEL', 'abc.xls'); ... DDE.Terminate(ConvID); END; ------------------------------------------------------------------

Make Your ASP Work With An Oracle Database
Hosted by www.Geocities.ws

1