A Bag of Tricks and Tips for DBAs and Developers Ari Kaplan Independent Consultant EOUG Madrid 2000.

30
A Bag of Tricks A Bag of Tricks and Tips for and Tips for DBAs and DBAs and Developers Developers Ari Kaplan Ari Kaplan Independent Consultant Independent Consultant EOUG Madrid 2000 EOUG Madrid 2000

Transcript of A Bag of Tricks and Tips for DBAs and Developers Ari Kaplan Independent Consultant EOUG Madrid 2000.

A Bag of Tricks A Bag of Tricks and Tips for and Tips for DBAs and DBAs and

DevelopersDevelopers

Ari KaplanAri KaplanIndependent ConsultantIndependent Consultant

EOUG Madrid 2000EOUG Madrid 2000

IntroductionIntroduction Most books and documentation are set

up like reference materials

Training courses focus on the

fundamental aspects of products in a

limited time

Hands-on experience is one of the best

ways to learn tricks to maximize your

use of Oracle

The Topics Dumping the contents of a table into an ASCI I delimited file

Getting around LONG datatype limitations

Using SQL to dynamically generate SQL scripts

Dynamically recreating your init.ora file

Finding all referencing constraints to a particular table

Finding the total REAL size of data in a table, not just the

I NI T/NEXT extent

What SQL statement is a particular user account executing?

Temporarily changing user passwords to log in as them

Dumping the Contents of a Dumping the Contents of a Table into an ASCII Delimited Table into an ASCII Delimited

FileFile Why do it?Why do it? Export/Import are used only with Oracle Export/Import are used only with Oracle

databasesdatabases You cannot always Export from one Oracle You cannot always Export from one Oracle

version and Import into anotherversion and Import into another ASCII files can be used to copy data from ASCII files can be used to copy data from

Oracle to other databases:Oracle to other databases:

SybaseSybase InformixInformix

Microsoft AccessMicrosoft Access ParadoxParadox

Microsoft SQL ServerMicrosoft SQL Server Microsoft ExcelMicrosoft Excel

email programsemail programs ParadoxParadox

FoxproFoxpro

Dumping the Contents of a Dumping the Contents of a Table into an ASCII Delimited Table into an ASCII Delimited

FileFileTo concatenate two columns in SQL statement, you use the concatenation symbol: ||To concatenate two columns in SQL statement, you use the concatenation symbol: ||

For example, assume there is a table such as that below:For example, assume there is a table such as that below:

EMPLOYEES TableEMPLOYEES Table

NAMENAME AGEAGE DEPARTMENTDEPARTMENT

David MaxDavid Max 2727 241241

Ari KaplanAri Kaplan 2828 242242

Mickey MouseMickey Mouse 100100 242242

DilbertDilbert 33 250250

You can spool the table with one record per line with the following SQL:You can spool the table with one record per line with the following SQL:

SELECT NAME||AGE||DEPARTMENT FROM EMPLOYEES;

Dumping the Contents of a Dumping the Contents of a Table into an ASCII Delimited Table into an ASCII Delimited

FileFileThe result of The result of SELECT NAME||AGE||DEPARTMENT FROM EMPLOYEES;SELECT NAME||AGE||DEPARTMENT FROM EMPLOYEES; will will

be:be:

David Max27241David Max27241

Ari Kaplan28242Ari Kaplan28242

Mickey Mouse100242Mickey Mouse100242

Dilbert3250Dilbert3250

You can see that the format does not separate columns. Typical formats include You can see that the format does not separate columns. Typical formats include

tabs to separate columns. In Oracle, this is represented with a CHR(9). So, a tabs to separate columns. In Oracle, this is represented with a CHR(9). So, a

better syntax would be the following SQL:better syntax would be the following SQL:

SELECT NAME||CHR(9)||AGE||CHR(9)||DEPARTMENT FROM SELECT NAME||CHR(9)||AGE||CHR(9)||DEPARTMENT FROM EMPLOYEES;EMPLOYEES;

The result will be:The result will be:

David MaxDavid Max 2727 241241

Ari KaplanAri Kaplan 2828 242242

Mickey MouseMickey Mouse 100100 242242

DilbertDilbert 33 250250

Dumping the Contents of a Table Dumping the Contents of a Table into an ASCII Delimited Fileinto an ASCII Delimited File

1) 1) SET HEADER OFFSET HEADER OFF

SET PAGESIZE 0SET PAGESIZE 0

SET FEEDBACK OFFSET FEEDBACK OFF

SET TRIMSPOOL ONSET TRIMSPOOL ON

2) 2) SPOOL file_name.txtSPOOL file_name.txt

<SQL statement><SQL statement>

3)3) SPOOL OFFSPOOL OFF

4)4) For tables where the length each record is greater than 80, be sure to set the For tables where the length each record is greater than 80, be sure to set the

LINESIZE value large enough. Otherwise Oracle will break up the lines every 80 LINESIZE value large enough. Otherwise Oracle will break up the lines every 80

characters, making the file not easily readable by other applications.characters, making the file not easily readable by other applications.

Getting Around LONG Datatype Getting Around LONG Datatype LimitationsLimitations

Overcoming the LONG columns:

Use BLOB datatypes and procedures with Oracle8. Oracle has already announced that it will discontinue LONG datatypes in a future release. You can convert LONG to LOB with the TO_LOB function.

Use PL/SQL to manipulate LONG datatype

Limitations:

LONG columns cannot do string manipulations

The CREATE TABLE table_A AS SELECT * FROM table_b cannot

be done if table_b has a LONG column

Snapshots and Replication have problems with LONG columns

Limit of one LONG column per table

Getting around LONG Datatype Getting around LONG Datatype LimitationsLimitations

Assume that there is a table:Assume that there is a table:

RESUME_BANKRESUME_BANK

NameName VARCHAR2(40)VARCHAR2(40)

DepartmentDepartment NUMBERNUMBER

Resume_textResume_text LONGLONG (stores the resume text)(stores the resume text)

Assume that you want to review all resumes with the word Assume that you want to review all resumes with the word

“ORACLE” in it. Normally, you would issue:“ORACLE” in it. Normally, you would issue:

SELECT resume_textSELECT resume_text

FROM resume_bankFROM resume_bank

WHERE UPPER(resume_bank) like ‘%ORACLE%’;WHERE UPPER(resume_bank) like ‘%ORACLE%’;

The result would be the ORA-932 “Inconsistent Datatypes”.The result would be the ORA-932 “Inconsistent Datatypes”.

Getting Around LONG Datatype LimitationsGetting Around LONG Datatype LimitationsTo find all such resume records with the LONG datatype in a table, you must use PL/SQL. Below is a To find all such resume records with the LONG datatype in a table, you must use PL/SQL. Below is a

sample program that will do this by selecting one resume from the resume bank:sample program that will do this by selecting one resume from the resume bank:

SET SERVEROUTPUT ON SIZE 100000;SET SERVEROUTPUT ON SIZE 100000;SET LONG 100000;SET LONG 100000;DECLAREDECLARELONG_varLONG_var LONG;LONG;resume_nameresume_name varchar2(40);varchar2(40);CURSOR x ISCURSOR x ISSELECT name, resume_text FROM RESUME_BANK;SELECT name, resume_text FROM RESUME_BANK;BEGINBEGINFOR cur_record in XFOR cur_record in Xresume_name := cur_record.name;resume_name := cur_record.name;LONG_var := cur_record.LONG_var;LONG_var := cur_record.LONG_var;

IF UPPER(resume_name) like ‘%ORACLE%’ THENIF UPPER(resume_name) like ‘%ORACLE%’ THEN/* Print the resume to the screen *//* Print the resume to the screen */

DBMS_OUTPUT.PUT_LINE(‘Below is the resume of ‘||resume_name||DBMS_OUTPUT.PUT_LINE(‘Below is the resume of ‘||resume_name|| ’ ’ that contains the word ORACLE:’);that contains the word ORACLE:’);

DBMS_OUTPUT.PUT_LINE(LONG_var);DBMS_OUTPUT.PUT_LINE(LONG_var);ENDIF;ENDIF;

END LOOP;END LOOP;END;END;//

Using SQL to Dynamically Generate SQL Using SQL to Dynamically Generate SQL ScriptsScripts

Why do this?Why do this?

The syntax to create a public synonym follows:The syntax to create a public synonym follows:

CREATE PUBLIC SYNONYM synonym_name FOR CREATE PUBLIC SYNONYM synonym_name FOR owner.table_name;owner.table_name;

The following statement will create a series of “CREATE PUBLIC SYNONYM” The following statement will create a series of “CREATE PUBLIC SYNONYM” statements:statements:

SELECT ‘SELECT ‘CREATE PUBLIC SYNONYMCREATE PUBLIC SYNONYM ‘|| object_name || ‘|| object_name ||

‘ ‘ FORFOR ‘ || owner || ‘ ‘ || owner || ‘..’ || object_name || ‘’ || object_name || ‘;;’’

FROM ALL_OBJECTSFROM ALL_OBJECTS

WHERE OWNER = ‘IOUG’;WHERE OWNER = ‘IOUG’;

This will produce an output similar to:This will produce an output similar to:

CREATE PUBLIC SYNONYM ATTENDEE FOR IOUG.ATTENDEE;CREATE PUBLIC SYNONYM ATTENDEE FOR IOUG.ATTENDEE;

CREATE PUBLIC SYNONYM HOTEL_ID FOR IOUG.HOTEL_ID;CREATE PUBLIC SYNONYM HOTEL_ID FOR IOUG.HOTEL_ID;

CREATE PUBLIC SYNONYM CREDIT_CARD_NBR FOR IOUG. CREATE PUBLIC SYNONYM CREDIT_CARD_NBR FOR IOUG. CREDIT_CARD_NBR;CREDIT_CARD_NBR;

Notice how there is a space in the original SQL statement between the FOR Notice how there is a space in the original SQL statement between the FOR and the preceding quote. Without the space, the output would look like...and the preceding quote. Without the space, the output would look like...

Using SQL to Dynamically Generate SQL Using SQL to Dynamically Generate SQL ScriptsScripts

The output from the previous SQL:

CREATE PUBLIC SYNONYM ATTENDEEFOR IOUG.ATTENDEE;

CREATE PUBLIC SYNONYM HOTEL_IDFOR IOUG.HOTEL_ID;

CREATE PUBLIC SYNONYM CREDIT_CARD_NBRFOR IOUG. CREDIT_CARD_NBR;

You can see how you must be careful of spaces and quotes.

Also, note the final concatenation with the semicolon (;)

1) 1) SET HEADER OFFSET HEADER OFF

SET PAGESIZE 0SET PAGESIZE 0

SET FEEDBACK OFFSET FEEDBACK OFF

2) 2) SPOOL file_name.sqlSPOOL file_name.sql

<SQL statement><SQL statement>

3)3) SPOOL OFFSPOOL OFF

44)) For output that is greater than 80 characters, be sure to For output that is greater than 80 characters, be sure to set the LINESIZE value large enough. Otherwise Oracle will set the LINESIZE value large enough. Otherwise Oracle will break up the lines every 80 characters, making the SQL break up the lines every 80 characters, making the SQL fail.fail.

Using SQL to Dynamically Using SQL to Dynamically Generate SQL ScriptsGenerate SQL Scripts

Putting it all together, the commands below will generate a Putting it all together, the commands below will generate a clean file that contains only proper SQL statements:clean file that contains only proper SQL statements:

SQL>SQL> SET HEAD OFF SET HEAD OFF

SQL>SQL> SET PAGESIZE 0 SET PAGESIZE 0

SQL>SQL> SET FEEDBACK OFF SET FEEDBACK OFF

SQL>SQL> SPOOL SPOOL create_synonym.SQLcreate_synonym.SQL

SQL>SQL> SELECT ‘CREATE PUBLIC SYNONYM ‘|| object_name || SELECT ‘CREATE PUBLIC SYNONYM ‘|| object_name ||

‘ ‘ FOR ‘ || owner || ‘.’ || object_name || ‘;’FOR ‘ || owner || ‘.’ || object_name || ‘;’

FROM ALL_OBJECTSFROM ALL_OBJECTS WHERE OWNER = ‘IOUG’; WHERE OWNER = ‘IOUG’;

CREATE PUBLIC SYNONYM ATTENDEE FOR IOUG.ATTENDEE;CREATE PUBLIC SYNONYM ATTENDEE FOR IOUG.ATTENDEE;

CREATE PUBLIC SYNONYM HOTEL_ID FOR IOUG.HOTEL_ID;CREATE PUBLIC SYNONYM HOTEL_ID FOR IOUG.HOTEL_ID;

CREATE PUBLIC SYNONYM CREDIT_CARD_NBR CREATE PUBLIC SYNONYM CREDIT_CARD_NBR

FOR IOUG. CREDIT_CARD_NBR;FOR IOUG. CREDIT_CARD_NBR;

SQL>SQL> SPOOL OFF SPOOL OFF

Dynamically Recreate Your INIT.ORA Dynamically Recreate Your INIT.ORA filefile

What is the INIT.ORA file?What is the INIT.ORA file? How can your INIT.ORA file get lost or out of synch?How can your INIT.ORA file get lost or out of synch? The The V$PARAMETER V$PARAMETER data dictionary view contains data dictionary view contains

the list of initialization parameters and their the list of initialization parameters and their values.values.NAMENAME TYPETYPE

NUMNUM NUMBERNUMBER

NAMENAME VARCHAR2(64)VARCHAR2(64)

TYPETYPE NUMBERNUMBER

VALUEVALUE VARCHAR2(512)VARCHAR2(512)

ISDEFAULTISDEFAULT VARCHAR2(9)VARCHAR2(9)

ISSES MODIFIABLEISSES MODIFIABLE VARCHAR2(5)VARCHAR2(5)

ISSYS MODIFIABLEISSYS MODIFIABLE VARCHAR2(9)VARCHAR2(9)

ISMODIFIEDISMODIFIED VARCHAR2(10)VARCHAR2(10)

ISADJUSTEDISADJUSTED VARCHAR2(5)VARCHAR2(5)

DESCRIPTIONDESCRIPTION VARCHAR2(64)VARCHAR2(64)

Dynamically Recreate Your INIT.ORA Dynamically Recreate Your INIT.ORA filefile

To see all of the parameters and their values (along To see all of the parameters and their values (along with whether or not they are the default values), with whether or not they are the default values), issue the following SQL:issue the following SQL:

SQL>SQL> COLUMN NAME FORMAT A30COLUMN NAME FORMAT A30

SQL>SQL> COLUMN VALUE FORMAT A30COLUMN VALUE FORMAT A30

SQL>SQL> SELECT NAME, VALUE, ISDEFAULTSELECT NAME, VALUE, ISDEFAULT

FROM V$PARAMETER ORDER BY NAME;FROM V$PARAMETER ORDER BY NAME;NAME VALUE ISDEFAULTshared_pool_size 300000000 FALSEsnapshot_refresh_interval 60 TRUEsnapshot_refresh_keep_connectFALSE TRUEsnapshot_refresh_process 0 TRUEsort_area_retained_size 0 TRUEsort_area_size 51200000 FALSEsort_direct_writes TRUE FALSEsort_spacemap_size 512 TRUEsort_write_buffer_size 32768 TRUE

Dynamically Recreate Your INIT.ORA Dynamically Recreate Your INIT.ORA filefile

To generate the INIT.ORA file, you can use SQL to To generate the INIT.ORA file, you can use SQL to generate SQL and spool the results to a file:generate SQL and spool the results to a file:

SQL>SQL> SET LINESIZE 200SET LINESIZE 200

SQL>SQL> SET TRIMSPOOL ONSET TRIMSPOOL ON

SQL>SQL> SET HEADING OFFSET HEADING OFF

SQL>SQL> SET FEEDBACK OFFSET FEEDBACK OFF

SQL>SQL> SET PAGESIZE 0SET PAGESIZE 0

SQL>SQL> SELECT NAME||’=‘||VALUESELECT NAME||’=‘||VALUE

22 FROM V$PARAMETER WHERE ISDEFAULT=‘FALSE’FROM V$PARAMETER WHERE ISDEFAULT=‘FALSE’

33 ORDER BY NAMEORDER BY NAME

SQL>SQL> SPOOL initSID.oraSPOOL initSID.ora

SQL>SQL> //

sequence_cache_entries=100sequence_cache_entries=100

sequence_cache_hash_buckets=89sequence_cache_hash_buckets=89

shared_pool_size=30000shared_pool_size=30000

sort_area_size=512000sort_area_size=512000

sort_direct_writes=TRUEsort_direct_writes=TRUE

rollback_segments=rbig, r01, r02, r03, r04rollback_segments=rbig, r01, r02, r03, r04

……

SQL>SQL> SPOOL OFFSPOOL OFF

Finding All Referencing Constraints to Finding All Referencing Constraints to a Particular Tablea Particular Table

The DBA_CONSTRAINTS data dictionary view The DBA_CONSTRAINTS data dictionary view contains information on table relationships:contains information on table relationships:

SQL>SQL> DESC DBA_CONSTRAINTSDESC DBA_CONSTRAINTS

NameName Null?Null? TypeTypeOWNEROWNER NOT NULLNOT NULL VARCHAR2(30)VARCHAR2(30)

CONSTRAINT_NAMECONSTRAINT_NAME NOT NULLNOT NULL VARCHAR2(30)VARCHAR2(30)

CONSTRAINT_TYPECONSTRAINT_TYPE VARCHAR2(1)VARCHAR2(1)

TABLE_NAMETABLE_NAME NOT NULLNOT NULL VARCHAR2(30)VARCHAR2(30)

SEARCH_CONDITIONSEARCH_CONDITION LONGLONG

R_OWNERR_OWNER VARCHAR2(30)VARCHAR2(30)

R_CONSTRAINT_NAMER_CONSTRAINT_NAME VARCHAR2(30)VARCHAR2(30)

DELETE_RULEDELETE_RULE VARHCAR2(9)VARHCAR2(9)

STATUSSTATUS VARCHAR2(8)VARCHAR2(8)

DEFERRABLEDEFERRABLE VARCHAR2(14)VARCHAR2(14)

DEFERREDDEFERRED VARCHAR2(9)VARCHAR2(9)

VALIDATEDVALIDATED VARCHAR2(13)VARCHAR2(13)

GENERATEDGENERATED VARCHAR2(14)VARCHAR2(14)

BADBAD VARCHAR2(3)VARCHAR2(3)

LAST_CHANGELAST_CHANGE DATEDATE

Finding All Referencing Constraints to Finding All Referencing Constraints to a Particular Tablea Particular Table

To see the constraints on the EMP and DEPT tables, To see the constraints on the EMP and DEPT tables, along with which constraints they are referencing:along with which constraints they are referencing:

SQL>SQL> SELECT OWNER||’.’||TABLE_NAME “TABLE”,SELECT OWNER||’.’||TABLE_NAME “TABLE”,

22 CONSTRAINT_NAME, R_CONSTRAINT_NAMECONSTRAINT_NAME, R_CONSTRAINT_NAME

33 FROM DBA_CONSTRAINTSFROM DBA_CONSTRAINTS

44 WHERE TABLE_NAME IN (‘EMP’,’DEPT’)WHERE TABLE_NAME IN (‘EMP’,’DEPT’)

TABLETABLE CONSTRAINT_NAMECONSTRAINT_NAME R_CONSTRAINT_NAMER_CONSTRAINT_NAME

SCOTT.EMPSCOTT.EMP FK_EMPFK_EMP PK_DEPT PK_DEPT

SCOTT.DEPTSCOTT.DEPT PK_DEPTPK_DEPT

Finding All Referencing Constraints to Finding All Referencing Constraints to a Particular Tablea Particular Table

To see all constraints that point to a table, issue:To see all constraints that point to a table, issue:SQL>SQL> SELECT OWNER||’.’||TABLE_NAME “TABLE”,SELECT OWNER||’.’||TABLE_NAME “TABLE”,

22 CONSTRAINT_NAME, R_CONSTRAINT_NAMECONSTRAINT_NAME, R_CONSTRAINT_NAME

33 FROM DBA_CONSTRAINTSFROM DBA_CONSTRAINTS

44 WHERE (OWNER, R_CONSTRAINT_NAME) INWHERE (OWNER, R_CONSTRAINT_NAME) IN

55 (SELECT OWNER, CONSTRAINT_NAME(SELECT OWNER, CONSTRAINT_NAME

66 FROM DBA_CONSTRAINTS B FROM DBA_CONSTRAINTS B

77 WHERE B.OWNER = ‘&owner’ ANDWHERE B.OWNER = ‘&owner’ AND

88 B.TABLE_NAME = ‘&table’);B.TABLE_NAME = ‘&table’);

Enter value for owner: Enter value for owner: SYSTEMSYSTEM

Enter value for table: Enter value for table: DEPTDEPT

TABLETABLE CONSTRAINT_NAMECONSTRAINT_NAME R_CONSTRAINT_NAMER_CONSTRAINT_NAME

SCOTT.EMPSCOTT.EMP FK_EMPFK_EMP PK_DEPT PK_DEPT

TRAINING.EMPTRAINING.EMP FK_EMPFK_EMP PK_DEPT PK_DEPT

Finding the Total Finding the Total REAL REAL Size of Data in Size of Data in a Table, Not Just the INIT/NEXT Extenta Table, Not Just the INIT/NEXT Extent

What are What are INITIALINITIAL and and NEXT NEXT extents?extents? How does data fill into extents?How does data fill into extents? Two possibilities: Two possibilities: ANALYZEANALYZE the table or the table or

use the use the ROWIDROWID pseudo-column pseudo-column ANALYZEANALYZE generates block statistics. generates block statistics. Oracle7’s Oracle7’s ROWID ROWID is in restricted format, is in restricted format,

which includes the blockwhich includes the block Oracle8’s Oracle8’s ROWIDROWID (extended format) can (extended format) can

be converted to restricted format with the be converted to restricted format with the DBMS_ROWID DBMS_ROWID package.package.

You can easily see the number of blocks that You can easily see the number of blocks that have been used by analyzing the table and have been used by analyzing the table and querying the USER_TABLES view:querying the USER_TABLES view:

SQL>SQL> ANALYZE TABLE ANALYZE TABLE table_nametable_name ESTIMATE STATISTICS; ESTIMATE STATISTICS;

Table Analyzed.Table Analyzed.

SQL>SQL> SELECT TABLE_NAME, BLOCKS, EMPTY_BLOCKS SELECT TABLE_NAME, BLOCKS, EMPTY_BLOCKS

22 FROM USER_TABLES WHERE TABLE_NAME = FROM USER_TABLES WHERE TABLE_NAME = ‘‘table_name’table_name’;;

TABLE_NAMETABLE_NAME BLOCKSBLOCKS EMPTY_BLOCKSEMPTY_BLOCKS

table_nametable_name 964 465 964 465

This will quickly give the results, but the This will quickly give the results, but the downsides are …downsides are …

Finding the Total Finding the Total REAL REAL Size of Data in Size of Data in a Table, Not Just the INIT/NEXT Extenta Table, Not Just the INIT/NEXT Extent

In Oracle7, to find out the total blocks, enter the following SQL:In Oracle7, to find out the total blocks, enter the following SQL:

SELECT count(distinct(substr(rowid,1,8))) FROM SELECT count(distinct(substr(rowid,1,8))) FROM table_nametable_name;; In Oracle8, you can find the total blocks using DBMS_ROWID:In Oracle8, you can find the total blocks using DBMS_ROWID:

SELECT SELECT count(distinct(substr(dbms_rowid.rowid_to_restricted(rowid),1,8))count(distinct(substr(dbms_rowid.rowid_to_restricted(rowid),1,8))))

FROM FROM table_nametable_name;;You will get the total number of blocks that contain records of the table.You will get the total number of blocks that contain records of the table.

To determine the overall size, find the block sizeTo determine the overall size, find the block size::

SELECT value FROM V$PARAMETER WHERE NAME = ‘db_block_size’;SELECT value FROM V$PARAMETER WHERE NAME = ‘db_block_size’; The total space of the data is the multiplication of “Total Blocks” The total space of the data is the multiplication of “Total Blocks” ** “Block “Block

Size”. This will be in bytes.Size”. This will be in bytes.

To find the density (rows per block for EACH block), issue (Oracle7):To find the density (rows per block for EACH block), issue (Oracle7):

SELECT distinct(substr(rowid,1,8)) FROM SELECT distinct(substr(rowid,1,8)) FROM table_nametable_name;;

-or in Oracle8--or in Oracle8-

SELECT (distinct(substr(dbms_rowid.rowid_to_restricted(rowid),1,8))SELECT (distinct(substr(dbms_rowid.rowid_to_restricted(rowid),1,8))

FROM FROM table_nametable_name;;

Finding the Total Finding the Total REAL REAL Size of Data in Size of Data in a Table, Not Just the INIT/NEXT Extenta Table, Not Just the INIT/NEXT Extent

What SQL Statement is a What SQL Statement is a Particular User Account Particular User Account

ExecutingExecuting One of the most important DBA jobs is to know One of the most important DBA jobs is to know

what the users are doingwhat the users are doing

Oracle does not make this easyOracle does not make this easy

Determine the SID of the user account you wish Determine the SID of the user account you wish to monitor. To get a list of all users logged in at to monitor. To get a list of all users logged in at any given time, type in the following SQL:any given time, type in the following SQL:

SELECT sid, schemaname, osuser, substr(machine, 1, 20) Machine

FROM v$session

ORDER BY schemaname;

A sample output follows:A sample output follows:

SIDSID SCHEMANAMESCHEMANAME OSUSEROSUSER MACHINEMACHINE-------- -------------------------------- ---------------------- ------------------------11 SYSSYS22 SYSSYS33 SYSSYS44 SYSSYS77 SYSTEMSYSTEM platplat ustate1ustate11313 SYSTEMSYSTEM oracleoracle ustate1ustate166 WWW_DBAWWW_DBA oracleoracle dw1-uwdw1-uw1414 WWW_DBAWWW_DBA oracleoracle dw1-uwdw1-uw1212 WWW_DBAWWW_DBA oracleoracle dw1-uwdw1-uw

What SQL Statement is a What SQL Statement is a Particular User Account Particular User Account

ExecutingExecuting

Now, you can select a user from list. When you Now, you can select a user from list. When you

run the SQL below, the SQL statement that run the SQL below, the SQL statement that

the user account is running will be shown.the user account is running will be shown.

SELECT sql_textSELECT sql_text

FROM v$sqlareaFROM v$sqlarea

WHERE (address, hash_value) INWHERE (address, hash_value) IN

((SELECT sql_address, sql_hash_valueSELECT sql_address, sql_hash_value

FROM v$sessionFROM v$session

WHERE sid = &1WHERE sid = &1););

What SQL Statement is a What SQL Statement is a Particular User Account Particular User Account

ExecutingExecuting

Temporarily Changing User Temporarily Changing User Passwords to Log in as Passwords to Log in as

ThemThem Can you determine a user’s password if you are Can you determine a user’s password if you are the DBA?the DBA?

How are passwords stored in the database?How are passwords stored in the database?

SELECT username, passwordSELECT username, password

FROM DBA_USERS;FROM DBA_USERS; You will get a result of something like:You will get a result of something like:

USERNAME USERNAME PASSWORD PASSWORD ..

AKAPLANAKAPLAN 923FEA35C3BE5824923FEA35C3BE5824

SYSTEMSYSTEM34D93E8F22C21DA434D93E8F22C21DA4

SYSSYSA943B39DF93E02C2A943B39DF93E02C2

There is a trick that you can use to temporarily change the users There is a trick that you can use to temporarily change the users

password to something you do know, and then change it back when password to something you do know, and then change it back when

you are done.you are done.

The unsuspecting user will never know ;)The unsuspecting user will never know ;)

Before you do this, you need to find the encrypted password:Before you do this, you need to find the encrypted password:

SELECT passwordSELECT password

FROM all_usersFROM all_users

WHERE username = ‘enter_username_here’;WHERE username = ‘enter_username_here’;

Temporarily Changing User Temporarily Changing User Passwords to Log in as Passwords to Log in as

ThemThem

Write down the 16-digit encrypted password. You will need Write down the 16-digit encrypted password. You will need this later. Now, change the password of the user to this later. Now, change the password of the user to whatever you want:whatever you want:

ALTER USER AKAPLAN IDENTIFIED BY ALTER USER AKAPLAN IDENTIFIED BY applaud_now;applaud_now;

You can now go into the database as the AKAPLAN user:You can now go into the database as the AKAPLAN user:

sqlplus AKAPLAN/applaud_nowsqlplus AKAPLAN/applaud_now To change the password back, use the “BY VALUES” clause To change the password back, use the “BY VALUES” clause

of the “ALTER USER” command. For the password, supply of the “ALTER USER” command. For the password, supply the 16-digit encrypted password in single quotes. An the 16-digit encrypted password in single quotes. An example is shown below:example is shown below:

ALTER USER AKAPLANALTER USER AKAPLAN

IDENTIFIED BY VALUES IDENTIFIED BY VALUES ‘923FEA35C3BE5824’;‘923FEA35C3BE5824’;

Temporarily Changing User Temporarily Changing User Passwords to Log in as Passwords to Log in as

ThemThem

FAILED_LOGIN_ATTEMPTSFAILED_LOGIN_ATTEMPTS

PASSWORD_GRACE_TIMEPASSWORD_GRACE_TIME

PASSWORD_LIFE_TIMEPASSWORD_LIFE_TIME

PASSWORD_LOCK_TIMEPASSWORD_LOCK_TIME

PASSWORD_REUSE_MAXPASSWORD_REUSE_MAX

PASSWORD_REUSE_TIMEPASSWORD_REUSE_TIME

PASSWORD_VERIFY_FUNCTIONPASSWORD_VERIFY_FUNCTION

Oracle8 Password-Related Management Options:Oracle8 Password-Related Management Options:Highlighted items are affected by temporarily changing Highlighted items are affected by temporarily changing

passwordspasswords

Temporarily Changing User Temporarily Changing User Passwords to Log in as Passwords to Log in as

ThemThem

Where to Now?Where to Now? There are many discussion Newsgroups on the internet for There are many discussion Newsgroups on the internet for

you to give questions and get answers:you to give questions and get answers:

comp.databases.oracle.servercomp.databases.oracle.server

comp.databases.oracle.toolscomp.databases.oracle.tools

comp.databases.oracle.misccomp.databases.oracle.misc

These can be accessed through a newsgroup program or These can be accessed through a newsgroup program or ““www.deja.comwww.deja.com””

Ari’s free Oracle Tips web page at:Ari’s free Oracle Tips web page at:

There are over 370 tips and answers to questions that have been posed to There are over 370 tips and answers to questions that have been posed to me over the years. This paper will be downloadable from the web page as me over the years. This paper will be downloadable from the web page as well.well.

Other good sites with links: Other good sites with links: www.orafaq.org, www.orafaq.org, www.orafans.com, www.ioug.org, www.orafans.com, www.ioug.org, www.orasearch.com, www.revealnet.com, www.orasearch.com, www.revealnet.com, www.lazydba.com, www.dbdomain.comwww.lazydba.com, www.dbdomain.com