Tuesday, November 6, 2012

11g File Watcher


http://docs.oracle.com/cd/E11882_01/server.112/e25494/scheduse005.htm
http://www.oracle-base.com/articles/11g/scheduler-enhancements-11gr2.php
http://awads.net/wp/2011/03/29/did-you-know-about-file-watchers/


A file watcher is a new scheduler object that enables a new type of even-based job that is triggered by the arrival of a file in a specified location. File watchers can be defined to monitor locations on the local server and remote servers, provided they have an agent installed on them.

We want oracle to import all the objects belonging to HR schema automatically whenever a .dmp file arrives in a specified folder on a system.
 To implement it we will use filewatcher which is a new scheduler object in oracle 11g. It  enables a new type of event-based job that is triggered by the arrival of a file in a specified location. File watchers can be defined to monitor locations on the local server and remote servers, provided they have an agent installed on them.

I am loading a file to a oracle table every day between 8 a.m and 9 a.m. The file may come at any time between 8 a.m to 9 a.m.
As of now, we are manually checking the file availability and then loading the file into oracle table.
My client is asking us to automate this process. My team is wondering if there is any way we can schedule based on file arrival in a specified location.


SELECT file_watcher_name, destination, directory_path, file_name, credential_name FROM user_scheduler_file_watchers;

SELECT file_watcher_name, destination, directory_path, file_name, credential_name FROM dba_scheduler_file_watchers;

SELECT * FROM   DBA_scheduler_credentials;

/* Configuration */
-- by default, a destination is checked every 10 mins.
To change this:
CONN / AS SYSDBA

set serveroutput on
declare v varchar2(1000);
begin
DBMS_SCHEDULER.GET_ATTRIBUTE ( 'FILE_WATCHER_SCHEDULE','REPEAT_INTERVAL', v);
DBMS_OUTPUT.PUT_LINE(V);
end;
/

BEGIN
DBMS_SCHEDULER.set_attribute('file_watcher_schedule','repeat_interval','freq=minutely;interval=1');
END;
/

/* Creating File Watcher */
-- create OS credential:

BEGIN
DBMS_SCHEDULER.create_credential(credential_name => 'fw_credential',username => 'Administrator',password => 'adminadmin@123');
END;
/

-- Grant EXECUTE on the credential to the schema that owns the
-- event-based job that the file watcher will start:


GRANT EXECUTE ON fw_credential to LDBO;

-- create file watcher:

BEGIN
DBMS_SCHEDULER.create_file_watcher(
file_watcher_name => 'data_fw',
directory_path => 'd:\ldoutput',  -- if '?' = ORACLE_HOME
file_name => '*.dat', -- wildcard supported
credential_name => 'fw_credential',
destination => NULL, -- NULL=local server
enabled => FALSE);
END;
/


-- Grant EXECUTE on the file watcher to any schema that owns an event-based job-- that references the file watcher.

GRANT EXECUTE ON data_fw to LDBO;

-- create a program raised by the file watcher

BEGIN
DBMS_SCHEDULER.create_program(
program_name => 'import_data_prog',
program_type => 'stored_procedure',
program_action => 'import_data_proc',
number_of_arguments => 1,
enabled => FALSE);
END;
/

-- define the metadata argument using the event_message attribute-- the metadata contains info about the file, such as its name:

BEGIN
DBMS_SCHEDULER.define_metadata_argument(
program_name => 'import_data_prog',
metadata_attribute => 'event_message',
argument_position => 1);
END;
/

-- create the defined procedure:-- It must accept an argument of the SCHEDULER_FILE WATCHER_RESULT type

DROP TABLE received_files ;

CREATE TABLE received_files ( fileinfo VARCHAR2(4000), rdate date );

CREATE OR REPLACE PROCEDURE import_data_proc
(p_sfwr SYS.SCHEDULER_FILEWATCHER_RESULT) AS
v_message received_files.fileinfo%type;
BEGIN
v_message := p_sfwr.directory_path || '\' || p_sfwr.actual_file_name || ' (' ||p_sfwr.file_size || ')';
INSERT INTO received_files VALUES (v_message, sysdate);
COMMIT;
END;
/

-- create the job:

BEGIN
DBMS_SCHEDULER.create_job(
job_name => 'import_data_job',
program_name => 'import_data_prog',
event_condition => NULL,      -- 'tab.user_data.file_size < 1024'
queue_spec => 'data_fw', -- file watcher name
auto_drop => FALSE,
enabled => FALSE);
END;
/

-- By default, the arrival of new files will be ignored if the job is already running.-- If you need the job to fire for each new arrival, regardless of whether the job isalready-- running or not, set the PARALLEL_INSTANCES attribute for the job to true. The job-- will then be run as a lightweight job:

BEGIN
DBMS_SCHEDULER.set_attribute('import_data_job','parallel_instances',TRUE);
END;
/

-- Enable all the objects:

EXEC DBMS_SCHEDULER.enable('data_fw,import_data_prog,import_data_job');

-- to test:
echo "This is a test" > D:\LDOUTPUT\f1.dat
echo "This is a test too" > D:\LDOUTPUT\f2.dat
echo "Yes another test" > D:\LDOUTPUT\f3.dat

select * from received_files order by rdate desc;

/* Managing File Watchers */
-- enable/disable
EXEC DBMS_SCHEDULER.enable('data_fw') ;
EXEC DBMS_SCHEDULER.disable('data_fw') ;

-- change an attribute:

begin
DBMS_SCHEDULER.SET_ATTRIBUTE (name => 'data_fw',attribute =>'directory_path',value =>'/home/oracle/receivedfiles' ) ;
end;
/

beginDBMS_SCHEDULER.SET_ATTRIBUTE(
name => 'data_fw',
attribute =>'file_name',
value =>'*.txt' ) ;
end;
/

begin
DBMS_SCHEDULER.SET_ATTRIBUTE (name => 'data_fw',attribute =>'credential_name',value =>'fw_credential2' ) ;
end;
/

-- to drop a file watchers:

EXEC DBMS_SCHEDULER.DROP_job('import_data_job');

EXEC DBMS_SCHEDULER.DROP_program('import_data_prog');

EXEC DBMS_SCHEDULER.DROP_FILE_WATCHER('data_fw');


BEGIN
DBMS_SCHEDULER.drop_credential(credential_name => 'fw_credential');
END;
/



--------------Enable the file watcher, the program, and the job

BEGIN
   DBMS_SCHEDULER.ENABLE('data_fw,import_data_prog,import_data_job');
END;
/




---------------------------------------------------

SELECT * FROM Dba_Scheduler_Job_Run_Details ORDER BY 1 DESC;

ORA-29538: Java not installed
ORA-06512: at "SYS.DBMS_ISCHED", line 3696
ORA-06512: at "SYS.DBMS_ISCHED", line 3907

ORA-29538 ORA-06512 FILE WATCHER

select * from product_component_version;
select comp_name,status from dba_registry;
select object_name from dba_objects where object_type like '%JAVA%' ;


set feedback on termout off
spool C:\install_java.log
@D:\app\Administrator\product\11.2.0\dbhome_1\javavm/install\initjvm.sql
@D:\app\Administrator\product\11.2.0\dbhome_1\xdk\admin\initxml.sql
@D:\app\Administrator\product\11.2.0\dbhome_1\xdk\admin\xmlja.sql
@D:\app\Administrator\product\11.2.0\dbhome_1\rdbms\admin\catjava.sql
@D:\app\Administrator\product\11.2.0\dbhome_1\rdbms\admin\catexf.sql
spool off

-------------Remove JVM:
SQL> @?/javavm/install/jvmrm.sql


-----------------------------Installing JVM on Oracle Database 11gR2
JVM was not installed on our Oracle 11gR2 database and we installed it manually by executing below steps from sqlplus login directly on the server [please follow all th steps]:

spool /home/oracle/ODMRINSTL/JVM/jvm_install.txt
set echo on
connect / as sysdba
shutdown immediate
startup mount
alter system set "_system_trig_enabled" = false scope=memory;
alter database open;
@?/javavm/install/initjvm.sql
@?/xdk/admin/initxml.sql
@?/xdk/admin/xmlja.sql
@?/rdbms/admin/catjava.sql
@?/rdbms/admin/catexf.sql
shutdown immediate
set echo off
spool off
exit

Verify with below queries & outputs:

SQL> select count(*), object_type from all_objects where object_type like '%JAVA%' group by object_type;

OWNER COUNT(*)
------ ----------
SYS 21313
EXFSYS 48

SQL> select comp_id,comp_name from dba_registry where comp_id in('CATJAVA','JAVAVM');

COMP_ID COMP_NAME
------- ------------------------------
JAVAVM JServer JAVA Virtual Machine
CATJAVA Oracle Database Java Packages

We have followed above for our case. For details and uninstallation please go through MOS Note:1112983.1 and prepare steps for your case.

-----------------------------------------------jssu.exe error on server

Problem signature:
  Problem Event Name: APPCRASH
  Application Name: jssu.exe
  Application Version: 0.0.0.0
  Application Timestamp: 4bb1e0d1
  Fault Module Name: StackHash_cc43
  Fault Module Version: 6.0.6001.18538
  Fault Module Timestamp: 4cb73957
  Exception Code: c0000374
  Exception Offset: 00000000000a7857
  OS Version: 6.0.6001.2.1.0.274.10
  Locale ID: 1033
  Additional Information 1: cc43
  Additional Information 2: dcf9b9d4873b0ed461caccd3a40f2997
  Additional Information 3: f0eb
  Additional Information 4: 0e4fbfefd1abdaa97da3f3d79632520f

Read our privacy statement:
  http://go.microsoft.com/fwlink/?linkid=50163&clcid=0x0409




ORA-29540: class schedFileWatcherJava does not exist
ORA-06512: at "SYS.DBMS_ISCHED", line 3744
ORA-06512: at "SYS.DBMS_ISCHED", line 3956

Monday, November 5, 2012

11g Migration using RMAN


The steps for 10g database:

1- Run the utlu112i.sql Pre-upgrade script. You can find this script under @$ORACLE_HOME/rdbms/admin/. It must be copied from the 11g database software.

SQL> @$ORACLE_HOME/rdbms/admin/utlu112i.sql

This script adds a column named tz_version to table named registry$database. Pre-upgrade script updates this column with the value of the following query.

SQL> select version from v$timezone_file;

So it performs following operation.

SQL> ALTER TABLE registry$database ADD (tz_version NUMBER);
SQL> UPDATE registry$database set tz_version =4;

SQL> ALTER  PACKAGE “SYS”.”DBMS_REGISTRY”  COMPILE BODY;
SQL> ALTER VIEW “SYS”.”DBA_REGISTRY_DATABASE”  COMPILE;

2- Connect to 10g database and take RMAN full backup.

#rman target /
RMAN> backup as backupset database;

3- Copy 10g database backup files and archive files to 11g database server.

The steps for 11g database:

1- Create temporary pfile in $ORACLE_HOME/dbs

*.audit_file_dest=’/oracle/admin/TALIPDB/adump’
*.compatible=’11.2.0.0.0′
*.control_files=’+DATA/talipdb/controlfile/current.257.787742981′,’+DATA/talipdb/controlfile/current.258.787742983′
*.db_block_size=8192
*.db_create_file_dest=’+DATA’
*.db_create_online_log_dest_1=’+RECO’
*.db_domain=”
*.db_name=’TALIPDB’
*.diagnostic_dest=’/oracle’
*.job_queue_processes=0
*.open_cursors=300
*.pga_aggregate_target=1G
*.processes=150
*.remote_login_passwordfile=’EXCLUSIVE’
*.sga_target=2G
*.undo_tablespace=’UNDOTBS1′

2- Open the database in NOMOUNT state.

# rman target /

RMAN> startup nomount;

3- Restore controlfile from backup.

RMAN> restore controlfile from ‘/oracle/ora11g/talipdb/backup/c-784951186-20120620-02′;

4- Open the database in MOUNT state.

RMAN> alter database mount;

5- Catalog RMAN backup files and archive log files.

RMAN> catalog start with ‘/oracle/ora11g/talipdb/backup’;
RMAN> catalog start with ‘/oracle/ora11g/talipdb/archive’;

6- Restore 10g database backup to +DATA diskgroup and perform incomplete recovery.

RMAN> run
{
allocate channel c1 device type disk;
SET NEWNAME FOR DATAFILE 1 TO ‘+DATA’;
SET NEWNAME FOR DATAFILE 2 TO ‘+DATA’;
SET NEWNAME FOR DATAFILE 3 TO ‘+DATA’;
SET NEWNAME FOR DATAFILE 4 TO ‘+DATA’;
restore database until sequence 4;
switch datafile all;
recover database until sequence 4;
}

7-  Open the database with RESETLOGS UPGRADE.

# sqlplus / as sysdba
SQL> alter database open resetlogs upgrade;

8- Run the upgrade script.

SQL> SPOOL upgrade.log
SQL> @$ORACLE_HOME/rdbms/admin/catupgrd.sql
SQL> SPOOL off

9- If our 10g and 11g database os platforms are different then you must run utlmmig.sql script.

————–Changing 32 bit to 64 bit————–
SQL> SHUTDOWN IMMEDIATE
SQL> STARTUP UPGRADE
SQL> SPOOL migrate.log
SQL> @$ORACLE_HOME/rdbms/admin/utlmmig.sql
SQL> SPOOL off
——————————————-

10- Now, you can open the database.

SQL> SHUTDOWN IMMEDIATE
SQL> STARTUP

11- Run the Post-Upgrade script to check problems.

SQL> @$ORACLE_HOME/rdbms/admin/utlu112s.sql

12- Compile invalid objects.

SQL> @$ORACLE_HOME/rdbms/admin/utlrp.sql

13- Drop the temporary file and create new one in +DATA diskgroup.

SQL> alter tablespace temp drop tempfile ‘/data_TALIPDB/temp01.dbf’;
SQL> alter tablespace temp add tempfile ‘+DATA’ size 1024M;

Listener ORA-00119 ORA-00132


Issues with setting Local Listener ORA-00119 ORA-00132


Today I was caught up in a issue with TNS while trying to setup SOA setup with OEM

Windows64bit machine

Database 11gr2

As per requirement we wanted to run the listener not on default port (1521 ) but some other port. Now as per Documentation if i want my non default port listener to register with pmon i need to set local_listener

“If you want PMON to register with a local listener that does not use TCP/IP, port 1521, then configure the LOCAL_LISTENER parameter in the initialization parameter file to locate the local listener.”

I though it will be a straight forward process just go ahead and run the alter system set local_listener=listener2 scope=both; but to surprise it didnt work as expected it returned an error

ERROR at line 1:
ORA-02097: parameter cannot be modified because specified value is invalid
ORA-00119: invalid specification for system parameter LOCAL_LISTENER
ORA-00132: syntax error or unresolved network name 'LISTENER2' … so a straightforward process didnt work as expected.


alter system set local_listener='(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=TAQVIA-IN.xx.xxx.com)(PORT=1522))))' sid='orcl64' scope=both





----------------------------------Startup fails with oracle error ORA-00119, ORA-00132-----------------------------------------------
Error Description:
---------------------------
Database Startup fails with oracle error ORA-00119, ORA-00132
SQL> startup mount
ORA-00119: invalid specification for system parameter LOCAL_LISTENER
ORA-00132: syntax error or unresolved network name 'LISTENER_DBASE'


Cause of The problem:
-------------------------
If the tnsnames.ora entry was used for the value of the LOCAL_LISTENER and the LOCAL_LISTENER entry inside tnsnames.ora is changed or tnsnames.ora file is moved and hence the tns alias to which the LOCAL_LISTENER parameter points is no longer valid. So, the entry inside spfile or pfile to be unresolvable, and the database will not start.

PMON must be able to resolve whatever value the LOCAL_LISTENER or REMOTE_LISTENER parameter is set to. Here LISTENER_DBASE is the name of the local listener.

Remember the LISTENER_DBASE is NOT the listener name reflected in the listener.ora file but rather it is an alias stored in the tnsnames.ora file.

Solution of The problem
-----------------------------
A)Correct the tnsnames.ora

i)Determine if the tns alias is good by using tnsping.

SQL> !tnsping LISTENER_DBASE
TNS Ping Utility for Solaris: Version 10.2.0.1.0 - Production on 15-MAY-2008 11:57:06
Copyright (c) 1997, 2005, Oracle. All rights reserved.

Used parameter files:
/oracle/app/oracle/product/10.2.0/db_1/network/admin/sqlnet.ora
TNS-03505: Failed to resolve name

So it could not find the name inside tnsnames.ora.
ii)
Add the LISTENER_DBASE entry in the tnsnames.ora file.

SQL> !vi /oracle/app/oracle/product/10.2.0/db_1/network/admin/tnsnames.ora
LISTENER_DBASE=(DESCRIPTION=(address=(protocol=tcp)(host=neptune)(port=1522)) (sid='dbase')

and run tnsping utility,

SQL> !tnsping LISTENER_DBASE
TNS Ping Utility for Solaris: Version 10.2.0.1.0 - Production on 15-MAY-2008 12:11:40
Copyright (c) 1997, 2005, Oracle. All rights reserved.
Used parameter files:
/oracle/app/oracle/product/10.2.0/db_1/network/admin/sqlnet.ora

Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION=(address=(protocol=tcp)(host=neptune)(port=1522)) (sid='dbase')
TNS-12533: TNS:illegal ADDRESS parameters

So there is syntax error in the LISTENER_DBASE alias. Correct it as here add parenthesis.

SQL> !vi /oracle/app/oracle/product/10.2.0/db_1/network/admin/tnsnames.ora
LISTENER_DBASE=(DESCRIPTION=(address=(protocol=tcp)(host=neptune)(port=1522)) (sid='dbase')))

iii)After correction run tnsping and start the database.
SQL> !tnsping LISTENER_DBASE
TNS Ping Utility for Solaris: Version 10.2.0.1.0 - Production on 15-MAY-2008 12:14:25
Copyright (c) 1997, 2005, Oracle. All rights reserved.
Used parameter files:
/oracle/app/oracle/product/10.2.0/db_1/network/admin/sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION=(address=(protocol=tcp)(host=neptune)(port=1522)) (sid='dbase'))
OK (0 msec)

SQL> startup
ORACLE instance started.
Total System Global Area 167772160 bytes
Fixed Size 2019288 bytes
Variable Size 83886120 bytes
Database Buffers 75497472 bytes
Redo Buffers 6369280 bytes
Database mounted.
Database opened.


B)An alternative solution is to remove the LOCAL_LISTENER entry from the listener.ora file.
1)Create spfile from pfile if you don't have pfile upadted.
SQL>CREATE PFILE FROM SPFILE;

2)Open the pfile and remove the LOCAL_LISTENER entry.

$vi /oracle/app/oracle/product/10.2.0/db_1/dbs/initdbase.ora

3)Create spfile from pfile.
SQL>CREATE PFILE FROM SPFILE;

4)Start the database.

SQL> startup
ORACLE instance started.
Total System Global Area 167772160 bytes
Fixed Size 2019288 bytes
Variable Size 83886120 bytes
Database Buffers 75497472 bytes
Redo Buffers 6369280 bytes
Database mounted.
Database opened.

Recommendation:
------------------
Though you can set the value of LOCAL_LISTENER (or REMOTE_LISTENER parameter if used) as alias in tnsnames.ora like in this example but it is not recommended setting. Instead use a full address descriptor inside pfile or set dynamically inside spfile.

In order to set dynamically inside spfile and in memory log in with dba privileges and issue:

ALTER SYSTEM set LOCAL_LISTENER="(address=(protocol=tcp)(host=yourhost)(port=yourport))" scope=both sid='instancename';

In my system,

SQL> ALTER SYSTEM set LOCAL_LISTENER="(address=(protocol=tcp)(host=neptune)(port=1522))" scope=both sid='dbase';

SQL> show parameter local

NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
local_listener string (address=(protocol=tcp)(host=neptune)(port=1522))

ora 12560 tns protocol adapter error database DBCA fails


ora 12560 tns protocol adapter error database DBCA fails

-------------------Most common reasons for ORA-12560 in Windows are----------------------------

- firewall (port 1521)
- DHCP and not using loopback adapter
- antivirus
-Windows Domain Control should not be installed(Oracle recommends to NOT install it on a domain controller.)
-There was no ORA_DBA group and no ORADBA user on the server




while creating database in oracle 11.2.0.1 using DBCA i am getting following error.

ora 12560 tns protocol adapter error

i am using administrator userid . any soultion for this

1)
It seems you use windows OS so go %ORACLE_HOME%\network\admin directory and edit sqlnet.ora then change/add context below text
SQLNET.AUTHENTICATION_SERVICES = (NTS)

same error

2) Don't Install from mstsc
Did you try creating database through remote or directly server? if remote then try it from directly server.


i tried directly from server. oracle database software installed successfully. After that database creation i am getting this error. After getting ora 12560 tns protocol adapter error
i added tnsnames through NETCA. After that i started dbca i am getting same error. Then i checked tnsnames.ora file the entry i added NETCA is not there in the file.please provide any solution

3)

Are there only one ORACLE_HOME?
Post there sqlnet.ora file context.
Did you get other error messages than ora 12560?

Only ione oracle_home is there.Other than ora 12560 i am not getting any error. The sqlnet.ora file is given below

# sqlnet.ora Network Configuration File: C:\Oracle\product\11.2.0\dbhome_1\network\admin\sqlnet.ora
# Generated by Oracle configuration tools.

# This file is actually generated by netca. But if customers choose to
# install "Software Only", this file wont exist and without the native
# authentication, they will not be able to connect to the database on NT.

SQLNET.AUTHENTICATION_SERVICES= (NTS)

NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)



4)

refer alert.log(C:\Oracle\product\11.2.0\diag\rdbms\<sid>\<db_unique_name>\trace directory)

In trace file i am getting following error in the OraVSSW file.
Could not execute [C:\Oracle\product\11.2.0\dbhome_1\bin\OraVSSW.exe ORAWH /d]; error 1


In this location no file is generated C:\Oracle\diag\rdbms


5)
ORA-12560 running DBCA on Windows 2008 AD Controller [ID 729774.1]


Another Solution:
Install the Oracle Software on a Non-Controller machine.
You can demote the Controller machine to a Member machine.
Perform the install, create the database.
Once everything is installed and setup, you can promote the machine to a Controller.
Be aware, you may have to go through these sames steps if you want to create another Database.


6) ORA-12560 - Database Creation Assistant (DBCA) Fails With TNS Error [ID 747243.1]

Cause
There was no ORA_DBA group and no ORADBA user on the server
System policies removed the group and/or the user used to install Oracl

Solution
After creating the group/user account (by matching the ones on the current production server), the DBCA ran to completion and created the database successfully.

Check with the sys admins to see if there is a policy or process in place to remove certain users and groups.  The ORA_DBA group and the Oracle user used for the installation must remain intact.

If the problem remains, after creating the group/user account, you might need to remove Oracle and reinstall the software.

Create Database Structure using Datapump


You can use the INSERT statement to insert data into a table, partition, or view in two ways: conventional INSERT and direct-path INSERT. When you issue a conventional INSERT statement, Oracle Database reuses free space in the table into which you are inserting and maintains referential integrity constraints. With direct-path INSERT, the database appends the inserted data after existing data in the table. Data is written directly into datafiles, bypassing the buffer cache. Free space in the existing data is not reused. This alternative enhances performance during insert operations and is similar to the functionality of the Oracle direct-path loader utility, SQL*Loader.

Direct-path INSERT is subject to a number of restrictions. If any of these restrictions is violated, then Oracle Database executes conventional INSERT serially without returning any message, unless otherwise noted:

You can have multiple direct-path INSERT statements in a single transaction, with or without other DML statements. However, after one DML statement alters a particular table, partition, or index, no other DML statement in the transaction can access that table, partition, or index.

Queries that access the same table, partition, or index are allowed before the direct-path INSERT statement, but not after it.

If any serial or parallel statement attempts to access a table that has already been modified by a direct-path INSERT in the same transaction, then the database returns an error and rejects the statement.

The target table cannot be index organized or part of a cluster.

The target table cannot contain object type columns.

The target table cannot have any triggers or referential integrity constraints defined on it.

The target table cannot be replicated.

A transaction containing a direct-path INSERT statement cannot be or become distributed.





Select Dbms_Metadata.Get_Ddl(Object_Type, Object_Name) From User_Objects WHERE OBJECT_TYPE IN ('TABLE','INDEX','LOB','PACKAGE','PACKAGE BODY','PROCEDURE','FUNCTION','TRIGGER');



best way to import full=Y content=metadata_only

and drop sequeunce, link, directories and recreate


G:\app\Administrator\product\11.2.0\dbhome_1\BIN\sqlplus.exe sys/oracle@apx1213srv as sysdba

CREATE DIRECTORY EXPDP11G AS 'd:\exp1213';

GRANT read, write ON DIRECTORY  EXPDP11G TO ldbo;

G:\app\Administrator\product\11.2.0\dbhome_1\BIN\impdp.exe ldbo/ldbo@nbs1213srv directory= EXPDP11G full=Y dumpfile=EXPDP11G.DMP logfile=expdp11meta.log content=metadata_only EXCLUDE=TABLESPACE,STATISTICS,DB_LINK,SEQUENCE


d:\app\Administrator\product\11.2.0\dbhome_1\bin\oradim.exe -delete -sid apx1314


select 'alter table '||table_name||' disable constraint '||constraint_name||';' from user_constraints;

G:\app\Administrator\product\11.2.0\dbhome_1\BIN\impdp.exe ldbo/ldbo@NBS1213srv full=Y directory=EXPDP11G dumpfile=EXPDP11G.DMP LOGFILE=nbs1314_data.LOG content=data_only data_options=skip_constraint_errors


----------------Final-----------------------EXP
d:\app\Administrator\product\11.2.0\dbhome_1\bin\expdp.exe ldbo/ldbo@nbs1112srv Full=Y directory=EXPDP11G dumpfile=apx1213metadata.DMP LOGFILE=apx1213metadata.LOG  content=metadata_only EXCLUDE=STATISTICS


----------------------
d:\app\Administrator\product\11.2.0\dbhome_1\bin\expdp.exe ldbo/ldbo@nbs1112srv directory=EXPDP11G dumpfile=apx1213metadata.DMP LOGFILE=apx1213metadata.LOG  content=metadata_only schemas=LDBO EXCLUDE=TABLESPACE,DB_LINK,DIRECTORY,JOB,STATISTICS,USER,ROLE,SEQUENCE

d:\app\Administrator\product\11.2.0\dbhome_1\bin\expdp.exe ldbo/ldbo@nbs1112srv directory=EXPDP11G dumpfile=apx1213userROLE.DMP LOGFILE=apx1213userROLE.LOG  content=metadata_only schemas=LDBO INCLUDE=USER,ROLE

d:\app\Administrator\product\11.2.0\dbhome_1\bin\expdp.exe ldbo/ldbo@nbs1112srv directory=EXPDP11G dumpfile=apx1213Synonyms.DMP LOGFILE=apx1213Synonyms.LOG  content=metadata_only INCLUDE=SYNONYM

-------------------------------------------IMP-----------------------------------------------create optable-----------------------------
d:\app\Administrator\product\11.2.0\dbhome_1\bin\impdp.exe ldbo/ldbo@nbs1314SRV directory=DATA_PUMP_DIR dumpfile=apx1213metadata.DMP LOGFILE=apx1213metadata.LOG schemas=LDBO EXCLUDE=TABLESPACE,DB_LINK,JOB,USER,ROLE,SEQUENCE sqlfile=optable.sql

d:\app\Administrator\product\11.2.0\dbhome_1\bin\impdp.exe ldbo/ldbo@nbs1314SRV directory=DATA_PUMP_DIR dumpfile=apx1213metadata.DMP LOGFILE=apx1213Synonyms.LOG INCLUDE=SYNONYM sqlfile=synonyms.sql


d:\app\Administrator\product\11.2.0\dbhome_1\bin\impdp.exe ldbo/ldbo@nbs1314SRV directory=DATA_PUMP_DIR dumpfile=apx1213metadata.DMP LOGFILE=apx1213Synonyms.LOG INCLUDE=PUBLIC_SYNONYM/SYNONYM:"IN (SELECT synonym_name FROM dba_synonyms WHERE table_owner='LDBO')"


d:\app\Administrator\product\11.2.0\dbhome_1\bin\impdp.exe ldbo/ldbo@nbs1314SRV directory=DATA_PUMP_DIR dumpfile=apx1213metadata.DMP LOGFILE=apx1213userROLE.LOG IMPDPINCLUDE=USER,ROLE_GRANT,SYSTEM_GRANT,GRANT,OBJECT_GRANT sqlfile=users.sql


D:\app\Administrator\product\11.2.0\dbhome_1\BIN\impdp.exe ldbo/ldbo@NBS1314srv directory=DATA_PUMP_DIR dumpfile=EXPDP11GFull.DMP LOGFILE=EXPDP11GFull.DMP.LOG schemas=LDBO table_exists_action=append data_options=skip_constraint_errors

D:\app\Administrator\product\11.2.0\dbhome_1\BIN\impdp.exe ldbo/ldbo@NBS1314srv directory=DATA_PUMP_DIR dumpfile=EXPDP11GFull.DMP LOGFILE=EXPDP11GFull.DMP.LOG schemas=LDBO table_exists_action=replace data_options=skip_constraint_errors

REPLACE option drop the current table in the database and the import recreate the new table as in the dumpfile.
----------------------------------------------------------------------IMPDP----------------------------------------------------------------------------------------------------------
d:\app\Administrator\product\11.2.0\dbhome_1\bin\impdp.exe ldbo/ldbo@nbs1314SRV directory=DATA_PUMP_DIR dumpfile=apx1213metadata.DMP LOGFILE=apx1213metadata.LOG schemas=LDBO EXCLUDE=TABLESPACE,DB_LINK,JOB,USER,ROLE,SEQUENCE transform=pctspace:70

 transform=pctspace:70 will reduce intial_extents, next_extents 70%.

select sum(initial_extent/1024/1024/1024) from user_tables;
select Sum(Initial_Extent/1024/1024/1024) from User_Indexes;


d:\app\Administrator\product\11.2.0\dbhome_1\bin\impdp.exe ldbo/ldbo@nbs1314SRV directory=DATA_PUMP_DIR dumpfile=apx1213metadata.DMP LOGFILE=apx1213Synonyms.LOG INCLUDE=SYNONYM

d:\app\Administrator\product\11.2.0\dbhome_1\bin\impdp.exe ldbo/ldbo@nbs1314SRV directory=DATA_PUMP_DIR dumpfile=apx1213metadata.DMP LOGFILE=apx1213userROLE.LOG INCLUDE=USER,ROLE

-------------------------------SEQUENCE CREATION--------------------------------------------
SELECT 'Create Sequence ' || Sequence_Name || ' minvalue ' ||   Min_Value || ' maxvalue ' || Max_Value || ' INCREMENT BY ' || Increment_By || ' CACHE ' || Cache_Size || ';' FROM USER_Sequences WHERE SEQUENCE_NAME NOT LIKE 'SQFIN%';

------------------------------------------------------------USER ROLE CREATION------------------------------------------------------------------------------------------------------------------------
SELECT 'CREATE ROLE ' ||ROLE || ';' FROM DBA_ROLES;

set head off
set pages 0
set long 9999999
spool c:\user_script.sql
SELECT DBMS_METADATA.GET_DDL('USER', USERNAME) || '/' DDL
FROM DBA_USERS
UNION ALL
SELECT DBMS_METADATA.GET_GRANTED_DDL('TABLESPACE_QUOTA', USERNAME) || '/' DDL
FROM DBA_USERS where username in (select username from dba_ts_quotas)
UNION ALL
SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT', USERNAME) || '/' DDL
FROM DBA_USERS where username in (select grantee from dba_role_privs)
UNION ALL
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT', USERNAME) || '/' DDL
FROM DBA_USERS where username in (select grantee from dba_sys_privs)
UNION ALL
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT', USERNAME) || '/' DDL
FROM DBA_USERS where username in (select grantee from dba_tab_privs);
spool off;



SELECT 'CREATE ROLE ' ||ROLE || ';' FROM DBA_ROLES;
Select 'GRANT ' || Privilege || ' ON ' ||Table_Name || ' TO "' || Grantee || '";' From Dba_Tab_Privs Where  OWNER='LDBO' ORDER BY GRANTEE,TABLE_NAME;
Select 'GRANT ' || Privilege || ' TO "' || Grantee || '";' From Dba_sys_Privs ORDER BY GRANTEE;
select 'GRANT ' || Privilege || ' (' || COLUMN_NAME ||  ') ON ' ||Table_Name || ' TO "' || Grantee || '";' from Dba_Col_Privs;
Select 'GRANT ' || Granted_Role || ' TO "' || Grantee || '";' From Dba_role_Privs ORDER BY GRANTEE;


---------------------------------DATABASE LINK CREATION

SELECT 'CREATE ' || OWNER || ' DATABASE LINK ' || DB_LINK || ' CONNECT TO ' || USERNAME || ' IDENTIFIED BY ' || '<PLEASE PUT PASSWORD>' || ' USING ' || '<PLEASE PUT DATABASE STRING>' || ';' FROM DBA_DB_LINKS  WHERE USERNAME !=' ';

SELECT 'DROP ' || OWNER || ' DATABASE LINK ' || DB_LINK || ';' FROM DBA_DB_LINKS WHERE USERNAME !=' ';



------------------------------------------DIRECTORY CREATION
select 'create directory '||OWNER||'.'||DIRECTORY_NAME||' as '||''''||DIRECTORY_PATH||''''||';' from dba_directories;

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Select Object_Type,Count(*) From User_Objects Group By Object_Type Order By 1;
select COUNT(*)  from user_objects where status='INVALID';
SELECT * FROM DBA_OBJECTS WHERE Owner='PUBLIC';
Select * From Dba_Synonyms Where Table_Owner='LDBO';
SELECT * FROM DBA_DB_LINKS;
SELECT * FROM DBA_DIRECTORIES;


EXEC sys.UTL_RECOMP.recomp_serial('LDBO');


Select * From  Dba_Tablespace_Usage_Metrics;

Select * From Dba_Hist_Tbspc_Space_Usage;

Select Sum(Bytes)/1024/1024, Sum(Bytes)/1024/1024/1024 FROM dba_data_files;----------------DATABASE SIZE

------------------------------------------------------------------------------------

INCLUDE=SYNONYM:"IN (SELECT synonym_name FROM dba_synonyms WHERE table_owner='LDBO')" sqlfile=synonyms.sql

INCLUDE=SYNONYM:\"in \(select synonym_name FROM dba_synonyms where table_owner like \'LDBO%\'\)\"

-----------------------------------------------------

EXCLUDE=SEQUENCE:\"in \(select SEQUENCE_NAME from USER_Sequences where SEQUENCE_NAME like \'SQFIN%\'\)\"

SELECT * FROM USER_Sequences WHERE SEQUENCE_NAME NOT LIKE 'SQFIN%';
-------------------------------MANUALLY CREATION

RECREATE SEQUENCE BECAUSE LAST NUMBER IS START WILL PREVIOUS YR VALUE
Users and roles are imported BUT RECREATE AGAIN SOME USER,OBJECT ROLES CAN MISSINGS

Select COUNT(*) From Dba_Users;
Select Count(*) From Dba_Roles;
Select COUNT(*) From Dba_Users;
Select Count(*) From Dba_Roles;
Select Grantee,Count(*) From Dba_Role_Privs Group By Grantee;
Select Grantee,Count(*) From Dba_TAB_Privs Group By Grantee;
Select * From Dba_Directories;
Select * From Dba_Db_Links;

SELECT 'Create Sequence ' || Sequence_Name || ' minvalue ' ||   Min_Value || ' maxvalue ' || Max_Value || ' INCREMENT BY ' || Increment_By || ' CACHE ' || Cache_Size || ';' FROM USER_Sequences WHERE SEQUENCE_NAME NOT LIKE 'SQFIN%';

-----------------

expdp ldbo/ldbo@apx1213srv full=Y directory=dpump_dir1 dumpfile=apx1213_meta.DMP LOGFILE=apx1213_meta.LOG  content=metadata_only

impdp ldbo/ldbo@apx1314srv full=Y directory=dpump_dir1 dumpfile=apx1213_meta.DMP LOGFILE=apx1314_meta.LOG EXCLUDE=DB_LINK,DIRECTORY,JOB,STATISTICS

impdp ldbo/ldbo@NBS1314srv full=Y directory=DATA_PUMP_DIR dumpfile=apx1213_meta.DMP LOGFILE=apx1314_meta.LOG EXCLUDE=DB_LINK,JOB,STATISTICS

IMPDP userid="'sys/oracle@NBS1314srv as sysdba'"  full=Y directory=DATA_PUMP_DIR dumpfile=apx1213_meta.DMP LOGFILE=apx1314_meta.LOG


D:\app\Administrator\product\11.2.0\dbhome_1\BIN\impdp.exe
------------------DATA IMPORT--------------

D:\app\Administrator\product\11.2.0\dbhome_1\BIN\impdp.exe ldbo/ldbo@NBS1314srv full=Y directory=EXPDP11G dumpfile=EXPDP11G15102012.DMP LOGFILE=apx1314.LOG content=data_only


----------------------------------------------------------



DIrectory=EXPORT_AUTO dumpfile=apx1213_SYSmeta.DMP LOGFILE=apx1213_SYSmeta.LOG content=metadata_only schemas=LDBO,SYS INCLUDE=PROCEDURE,TRIGGER


EXCLUDE=DB_LINK,DIRECTORIES,JOB,STATISTICS




exec dbms_stats.delete_database_stats;

1) Users and roles are imported BUT RECREATE AGAIN SOME USER,OBJECT ROLES CAN MISSINGS


Select * From Dba_Users;
SELECT * FROM DBA_ROLES;
Select * From Dba_Role_Privs;
Select * From Dba_TAB_Privs;
Select * From Dba_SYS_Privs;

Select * From Dba_Directories;
Select * From Dba_Db_Links;

SELECT * FROM Dba_Scheduler_Jobs;


BEGIN sys.UTL_RECOMP.recomp_serial('LDBO'); END;
/

select object_name from user_objects where status='INVALID';

SELECT * FROM Dba_Scheduler_Jobs;

SELECT * FROM Dba_Objects WHERE OBJECT_NAME IN ('SPLOGININFORMATION','TGLOGININFORMATION');

CREATE SPLOGININFORMATION,TGLOGININFORMATION MANUALLY

DROP SEQUENCE
SELECT * FROM USER_Sequences WHERE SEQUENCE_NAME LIKE 'SQFIN%';



DATABASE LINK 2
FUNCTION 137
INDEX 730
JOB 21
LOB 255
PACKAGE 115
PACKAGE BODY 115
PROCEDURE 443
QUEUE 6
SEQUENCE 505
TABLE 981
TABLE PARTITION 368
TRIGGER 250
TYPE 13
VIEW 32


Select Tablespace_Name,SUM(bytes/1024/1024/1024) From DBA_Extents GROUP BY Tablespace_Name;




now let’s generate it again but using the transform parameter to reduce the size of it to 70% of original size.

impdp user/password transform=pctspace:70 content=metadata_only directory=datapump dumpfile=ex.dmp



before is to import it telling the Data Pump to reduce the size of extents to 70%


http://oraclenz.wordpress.com/2010/04/29/tip-of-the-month-how-to-have-super-powers-using-data-pump/

http://www.dba-oracle.com/t_data_pump_pctspace.htm




root> impdp transform=pctspace:25

This tells the impdp (import) to re-size the tablespace to 25% of its original size.

 when the table actually gets imported than the extent sizes are same.


impdp scott1/tiger1 directory=dump_dir dumpfil
e=SCOTT1.DMP logfile=import1.log remap_schema=scott:scott1 SQLFILE=dump_dir:SQLf
ile2.log TRANSFORM=PCTSPACE:70


select
  tablespace_name,
   file_id,
   owner,
   segment_name,
   block_id begin,
   blocks,
   block_id+blocks-1 end,
   bytes/1024 KB,
   '' free
from sys.dba_extents
where tablespace_name not in ('RBS','SYSTEM','TEMP','TOOLS','USER')
union
select
   tablespace_name,
   file_id,
   '' owner,
   '' segment_name,
   block_id begin,
   blocks,
   block_id+blocks+1 end,
   bytes/1023 KB,
   'F' free
from sys.dba_free_space
where tablespace_name not in ('RBS','SYSTEM','TEMP','TOOLS','USER')
order by 1, 2, 5
;

For IMPORT:
$impdp parfile=import.par

import.par file contains :

full=y
directory=dump_files1
dumpfile=CR06172102_%Uexport.dmp
logfile=CR06172102_import.log
job_name=CR06172102_import
parallel=8
EXCLUDE=TABLESPACE
EXCLUDE=DIRECTORY
EXCLUDE=SCHEMA:"='TSMSYS'"
EXCLUDE=SCHEMA:"='SYS'"
EXCLUDE=SCHEMA:"='SYSTEM'"
EXCLUDE=SCHEMA:"='WMSYS'"
EXCLUDE=SCHEMA:"='DBSNMP'"
EXCLUDE=SCHEMA:"='OUTLN'"
EXCLUDE=SCHEMA:"='SYSMAN'"
EXCLUDE=SCHEMA:"='ANONYMOUS'"
EXCLUDE=SCHEMA:"='CTXSYS'"
EXCLUDE=SCHEMA:"='DIP'"
EXCLUDE=SCHEMA:"='ORAMAN'"
EXCLUDE=SCHEMA:"='XDB'"

expdp "'/ as sysdba'" DIRECTORY=DPDUMP_HRDB_DIR1 DUMPFILE=TRANS_HRDB%U.dmp LOGFILE=TRANS_HRDB.log FULL=Y "EXCLUDE=TABLESPACE,PROFILE,DIRECTORY,statistics,SCHEMA:\"IN ('ARCHIVE_USER','TRANS_HRDB','GLOBAL_HRDB','GLOBAL_INTERFACE_USER','TRANS_HRDD','PERF_DIRECT','GCM_DATA','GCM_APP','COMP','COMP_HIST','SYS','SYSTEM','SYSMAN','RMANUSER','RMAN','EXFSYS','WMSYS','DBSNMP')\"" PARALLEL=4



------------------------------Error

Oracle Bug ID 1434393.1
DataPump Import (IMPDP) With CONTENT=DATA_ONLY Fails With Error ORA-39126 Worker unexpected fatal error in KUPW$WORKER.UPATE_TD_ROW_IMP [ID 1434393.1]


Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit
Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
Master table "LDBO"."SYS_IMPORT_SCHEMA_01" successfully loaded/unloaded
Starting "LDBO"."SYS_IMPORT_SCHEMA_01":  ldbo/********@NBS1314srv directory=DAT
_PUMP_DIR dumpfile=EXPDP11GFull.DMP LOGFILE=EXPDP11GFull.DMP.LOG content=data_only schemas=LDBO
Processing object type DATABASE_EXPORT/SCHEMA/TABLE/TABLE_DATA
ORA-39126: Worker unexpected fatal error in KUPW$WORKER.UPATE_TD_ROW_IMP [112]
TABLE_DATA:"LDBO"."SCHEDULER$_JOB_ARG"
ORA-31603: object "SCHEDULER$_JOB_ARG" of type TABLE not found in schema "LDBO"

ORA-06512: at "SYS.DBMS_SYS_ERROR", line 105
ORA-06512: at "SYS.KUPW$WORKER", line 8171

----- PL/SQL Call Stack -----
  object      line  object
  handle    number  name
000007FFB3973380     18990  package body SYS.KUPW$WORKER
000007FFB3973380      8192  package body SYS.KUPW$WORKER
000007FFB3973380     18552  package body SYS.KUPW$WORKER
000007FFB3973380      4105  package body SYS.KUPW$WORKER
000007FFB3973380      8875  package body SYS.KUPW$WORKER
000007FFB3973380      1649  package body SYS.KUPW$WORKER
000007FFB360AD30         2  anonymous block

ORA-39126: Worker unexpected fatal error in KUPW$WORKER.UPATE_TD_ROW_IMP [112]
TABLE_DATA:"LDBO"."SCHEDULER$_JOB_ARG"
ORA-31603: object "SCHEDULER$_JOB_ARG" of type TABLE not found in schema "LDBO"

ORA-06512: at "SYS.DBMS_SYS_ERROR", line 105
ORA-06512: at "SYS.KUPW$WORKER", line 8171

----- PL/SQL Call Stack -----
  object      line  object
  handle    number  name
000007FFB3973380     18990  package body SYS.KUPW$WORKER
000007FFB3973380      8192  package body SYS.KUPW$WORKER
000007FFB3973380     18552  package body SYS.KUPW$WORKER
000007FFB3973380      4105  package body SYS.KUPW$WORKER
000007FFB3973380      8875  package body SYS.KUPW$WORKER
000007FFB3973380      1649  package body SYS.KUPW$WORKER
000007FFB360AD30         2  anonymous block

Job "LDBO"."SYS_IMPORT_SCHEMA_01" stopped due to fatal error at 15:12:28






. . imported "LDBO"."TBLAUDITEMAILACCOUNTDETAIL"         688.8 MB  389588 rows
ORA-31693: Table data object "LDBO"."JOURNDRCR" failed to load/unload and is being skipped due to error:
ORA-29913: error in executing ODCIEXTTABLEFETCH callout
ORA-02291: integrity constraint (LDBO.JOURNALCODE) violated - parent key not found

C:\Users\Administrator>G:\app\Administrator\product\11.2.0\dbhome_1\BIN\impdp.exe ldbo/ldbo@apx1213srv directory= EXPDP11G dumpfile=expdp11g.dmp logfile=expdp11meta.log SCHEMAS=LDBO content=DATA_ONLY data_options=skip_constraint_errors

Processing object type DATABASE_EXPORT/SCHEMA/TABLE/TABLE_DATA
ORA-39034: Table TABLE_DATA:"LDBO"."SCHEDULER$_JOB_ARG" does not exist.



C:\Users\Administrator>G:\app\Administrator\product\11.2.0\dbhome_1\BIN\impdp.exe ldbo/ldbo@apx1213srv directory= EXPDP11G dumpfile=expdp11g.dmp logfile=expdp11meta.log  Tables=scheduler$_JOB_arg

C:\Users\Administrator>G:\app\Administrator\product\11.2.0\dbhome_1\BIN\impdp.exe ldbo/ldbo@apx1213srv directory= EXPDP11G dumpfile=expdp11g.dmp logfile=expdp11meta.log SCHEMAS=LDBO content=DATA_ONLY data_options=skip_constraint_errors

Saturday, November 3, 2012

Create Schema Objects


Note: This will not work from 10g to 11g version......................procedure will be corrupted


set pagesize 0
set linesize 30000
set long 500000
set longchunksize 500000
set trimspool on
set feed off

exec dbms_metadata.set_transform_param(dbms_metadata.session_transform,'PRETTY',true);
exec dbms_metadata.set_transform_param( DBMS_METADATA.SESSION_TRANSFORM, 'SQLTERMINATOR', TRUE );
exec  dbms_metadata.set_transform_param(dbms_metadata.session_transform,'CONSTRAINTS',false);
exec  dbms_metadata.set_transform_param (dbms_metadata.session_transform,'REF_CONSTRAINTS', false);
exec dbms_metadata.set_transform_param(dbms_metadata.session_transform, 'CONSTRAINTS_AS_ALTER', false);

SPOOL C:\OPTABLE.SQL
select dbms_metadata.get_ddl('SYNONYM',synonym_name,'PUBLIC') metadata from dba_synonyms where owner = 'PUBLIC'   and table_owner = 'LDBO' ;
Select Dbms_Metadata.Get_Ddl('SEQUENCE',Sequence_Name)  from User_Sequences Where Sequence_Name Not Like 'SQFIN_%';
Select Dbms_Metadata.Get_Ddl(Object_Type, Object_Name) From User_Objects WHERE OBJECT_TYPE = 'TABLE';
Select Dbms_Metadata.Get_Ddl(Object_Type, Object_Name) From User_Objects WHERE OBJECT_TYPE IN 'INDEX' ;
Select Dbms_Metadata.Get_Ddl('CONSTRAINT', Constraint_Name) Ddl FROM USER_CONSTRAINTS WHERE Constraint_Type='C' And Constraint_Name Not Like 'BIN%'  order by table_name;
Select Dbms_Metadata.Get_Ddl(decode(constraint_type, 'R', 'REF_CONSTRAINT', 'CONSTRAINT'), constraint_name, owner)  CONSDDL From Dba_Constraints WHERE owner='LDBO' AND CONSTRAINT_NAME NOT LIKE 'BIN$%' and constraint_type IN('P', 'R', 'U') Order By Case When Constraint_Type In('P','U') Then 0 Else 1 End;
Select Dbms_Metadata.Get_Ddl(Object_Type, Object_Name) From User_Objects WHERE OBJECT_TYPE IN ('PROCEDURE','FUNCTION','TYPE');
Select Dbms_Metadata.Get_Ddl('PACKAGE_SPEC', Object_Name)  From User_Objects WHERE OBJECT_TYPE IN ('PACKAGE');
Select Dbms_Metadata.Get_Ddl('PACKAGE_BODY', Object_Name) From User_Objects WHERE OBJECT_TYPE IN ('PACKAGE BODY');
Select Dbms_Metadata.Get_Ddl(Object_Type, Object_Name) From User_Objects WHERE OBJECT_TYPE IN ('TRIGGER');

SELECT DBMS_METADATA.GET_DDL('USER', USERNAME) FROM DBA_USERS;
SELECT DBMS_METADATA.GET_GRANTED_DDL('TABLESPACE_QUOTA', USERNAME) DDL FROM DBA_USERS where username in (select username from dba_ts_quotas);
SELECT DBMS_METADATA.GET_DDL('ROLE', role) FROM dba_roles;
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT', GRANTEE) FROM DBA_SYS_PRIVS;
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT', GRANTEE) FROM DBA_TAB_PRIVS WHERE OWNER='LDBO';
SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT', GRANTEE) FROM DBA_ROLE_PRIVS;
SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT', USERNAME) DDL FROM DBA_USERS where username in (select grantee from dba_role_privs);
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT', USERNAME) DDL FROM DBA_USERS where username in (select grantee from dba_sys_privs)
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT', USERNAME) DDL FROM DBA_USERS where username in (select grantee from dba_tab_privs);
spool off



--------------------------------------------------------------objects---------------------------------------------------------

db_link
sequence
directory
synonym
type
table
index
constraint
package
function
procedure
compile invalid
view
ref_constra
package body
type body
trigger
MATERIALIZED_VIEW
MATERIALIZED_VIEW_LOG
JOB

--------------------------------------------checking------------------------------------------------------------------

Select Object_Type,Count(*) From User_Objects Group By Object_Type Order By 1;
select COUNT(*)  from user_objects where status='INVALID';
SELECT * FROM DBA_OBJECTS WHERE Owner='PUBLIC';
Select * From Dba_Synonyms Where Table_Owner='LDBO';
SELECT * FROM DBA_DB_LINKS;
SELECT * FROM DBA_DIRECTORIES;
select Constraint_Type,count(*) from User_Constraints group by Constraint_Type;
select table_name,count(*) from User_Constraints group by table_name order by 1;
select table_name,Search_Condition from User_Constraints where Constraint_Type='C' and table_name not like 'BIN%' ORDER BY 1;


---------------------------------------------------------------Directory Creation-------------------------------------------

select 'create directory '||OWNER||'.'||DIRECTORY_NAME||' as '||''''||DIRECTORY_PATH||''''||';' from dba_directories;
or
select dbms_metadata.get_ddl('DIRECTORY',directory_name) from dba_Directories;


get and change the path as you want


------------------------------------------------------------------Database link--------------------------------------------

SELECT 'CREATE ' || OWNER || ' DATABASE LINK ' || DB_LINK || ' CONNECT TO ' || USERNAME || ' IDENTIFIED BY ' || '<PLEASE PUT PASSWORD>' || ' USING ' || '<PLEASE PUT DATABASE STRING>' || ';' FROM DBA_DB_LINKS  WHERE USERNAME !=' ';

Select 'DROP '||Decode(U.Name,'PUBLIC','public ')||'database link '||Chr(10)
||Decode(U.Name,'PUBLIC',Null, U.Name||'.')|| L.Name||Chr(10) ||';' TEXT
From Sys.Link$ L, Sys.User$ U
Where L.Owner# = U.User#;

SELECT 'create '||DECODE(U.NAME,'PUBLIC','public ')||'database link '||CHR(10)
||Decode(U.Name,'PUBLIC',Null, U.Name||'.')|| L.Name||Chr(10)
||' connect to ' || L.Userid || ' identified by values '''
||L.PASSWORDX||''' using ''' || L.host || ''''
||chr(10)||';' TEXT
From Sys.Link$ L, Sys.User$ U
WHERE L.OWNER# = U.USER# AND L.USERID !=' ';



CREATE PUBLIC DATABASE LINK "LNK_RAKSHAK"
  CONNECT TO "LDBO" IDENTIFIED BY LDBO USING 'APX1314SRV';

 CREATE PUBLIC DATABASE LINK "LNK_CCM"
  CONNECT TO "LDBO" IDENTIFIED BY LDBO USING 'APX1314SRV';

CREATE DATABASE LINK "LNK_DIGITAL"
  CONNECT TO "LDBO" IDENTIFIED BY ldbo USING 'APX1314SRV';

create database link LNK_PREVIOUSYEARBALANCE connect to LDBO identified by ldbo using 'APX1314SRV';

CREATE PUBLIC DATABASE LINK "CMLDLINK"
  CONNECT TO ldbo IDENTIFIED BY ldbo USING 'APX1314SRV';


--------------------------------------------------------------------------------------------------------------

set pagesize 0
set linesize 30000
set long 500000
set longchunksize 500000
set trimspool on
set feed off

exec dbms_metadata.set_transform_param(dbms_metadata.session_transform,'PRETTY',true);
exec dbms_metadata.set_transform_param( DBMS_METADATA.SESSION_TRANSFORM, 'SQLTERMINATOR', TRUE );
exec  dbms_metadata.set_transform_param(dbms_metadata.session_transform,'CONSTRAINTS',false);
exec  dbms_metadata.set_transform_param (dbms_metadata.session_transform,'REF_CONSTRAINTS', false);
exec dbms_metadata.set_transform_param(dbms_metadata.session_transform, 'CONSTRAINTS_AS_ALTER', false);


SPOOL C:\SEQ.SQL
Select Dbms_Metadata.Get_Ddl('SEQUENCE',Sequence_Name)  from User_Sequences Where Sequence_Name Not Like 'SQFIN_%';
SPOOL OFF

spool c:\tables.sql
Select Dbms_Metadata.Get_Ddl(Object_Type, Object_Name) From User_Objects WHERE OBJECT_TYPE = 'TABLE';
spool off

spool c:\index.sql
Select Dbms_Metadata.Get_Ddl(Object_Type, Object_Name) From User_Objects WHERE OBJECT_TYPE IN 'INDEX' ;
spool off

spool c:\syn.sql
select dbms_metadata.get_ddl('SYNONYM',synonym_name,'PUBLIC') metadata from dba_synonyms where owner = 'PUBLIC'   and table_owner = 'LDBO' ;
spool off

spool c:\consc.sql
Select Dbms_Metadata.Get_Ddl('CONSTRAINT', Constraint_Name) Ddl FROM USER_CONSTRAINTS WHERE Constraint_Type='C' And Constraint_Name Not Like 'BIN%'  order by table_name;
spool off


spool c:\consp.sql
Select Dbms_Metadata.Get_Ddl(
decode(constraint_type, 'R', 'REF_CONSTRAINT', 'CONSTRAINT'), constraint_name, owner)  CONSDDL
From Dba_Constraints
WHERE owner='LDBO' AND CONSTRAINT_NAME NOT LIKE 'BIN$%'
and constraint_type IN('P', 'R', 'U')
Order By Case When Constraint_Type In('P','U') Then 0 Else 1 End;
spool off


spool c:\proc.sql
Select Dbms_Metadata.Get_Ddl(Object_Type, Object_Name) From User_Objects WHERE OBJECT_TYPE IN ('PROCEDURE','FUNCTION','TYPE');
spool off

spool c:\pack.sql
Select Dbms_Metadata.Get_Ddl('PACKAGE_SPEC', Object_Name)  From User_Objects WHERE OBJECT_TYPE IN ('PACKAGE');
spool off

spool c:\packb.sql
Select Dbms_Metadata.Get_Ddl('PACKAGE_BODY', Object_Name) From User_Objects WHERE OBJECT_TYPE IN ('PACKAGE BODY');
spool off

spool c:\trigger.sql
Select Dbms_Metadata.Get_Ddl(Object_Type, Object_Name) From User_Objects WHERE OBJECT_TYPE IN ('TRIGGER');
spool off


------------------------------------------------------------------User Creation and its role--------------------------------------------
set head off
set pages 0
set long 9999999
spool c:\user_script.sql
SELECT DBMS_METADATA.GET_DDL('USER', USERNAME) || '/' DDL
FROM DBA_USERS
UNION ALL
SELECT DBMS_METADATA.GET_GRANTED_DDL('TABLESPACE_QUOTA', USERNAME) || '/' DDL
FROM DBA_USERS where username in (select username from dba_ts_quotas)
UNION ALL
SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT', USERNAME) || '/' DDL
FROM DBA_USERS where username in (select grantee from dba_role_privs)
UNION ALL
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT', USERNAME) || '/' DDL
FROM DBA_USERS where username in (select grantee from dba_sys_privs)
UNION ALL
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT', USERNAME) || '/' DDL
FROM DBA_USERS where username in (select grantee from dba_tab_privs);
spool off;



--------------------------------------------------------------Role Creation------------------------------------------------------------------

SELECT 'CREATE ROLE ' ||ROLE || ';' FROM DBA_ROLES;
Select 'GRANT ' || Privilege || ' ON ' ||Table_Name || ' TO "' || Grantee || '";' From Dba_Tab_Privs Where  OWNER='LDBO' ORDER BY GRANTEE,TABLE_NAME;
Select 'GRANT ' || Privilege || ' TO "' || Grantee || '";' From Dba_sys_Privs ORDER BY GRANTEE;
select 'GRANT ' || Privilege || ' (' || COLUMN_NAME ||  ') ON ' ||Table_Name || ' TO "' || Grantee || '";' from Dba_Col_Privs;
Select 'GRANT ' || Granted_Role || ' TO "' || Grantee || '";' From Dba_role_Privs ORDER BY GRANTEE;


-----------------------------------------------------------------------------------User Role Profile


select dbms_metadata.get_ddl('USER', u.username) AS ddl from   dba_users u
union all
select dbms_metadata.get_ddl('ROLE', role) AS ddl FROM dba_roles
union all
select dbms_metadata.get_granted_ddl('TABLESPACE_QUOTA', tq.username) AS ddl from   dba_ts_quotas tq
union all
select dbms_metadata.get_granted_ddl('ROLE_GRANT', rp.grantee) AS ddl from   dba_role_privs rp
union all
select dbms_metadata.get_granted_ddl('SYSTEM_GRANT', sp.grantee) AS ddl from dba_sys_privs sp
union all
select dbms_metadata.get_granted_ddl('OBJECT_GRANT', tp.grantee) AS ddl from   dba_tab_privs tp
union all
select dbms_metadata.get_granted_ddl('DEFAULT_ROLE', rp.grantee) AS ddl from   dba_role_privs rp
union all
select to_clob('/* Start profile creation script in case they are missing') AS ddl from dba_users u where u.profile <> 'DEFAULT'
union all
select dbms_metadata.get_ddl('PROFILE', u.profile) AS ddl from   dba_users u where   u.profile <> 'DEFAULT'
union all
select to_clob('End profile creation script */') AS ddl from   dba_users u where u.profile <> 'DEFAULT'
;

-----------------------------------------------------------------------------------

set define off
Turns off substitution variables.

---------------------------------------------------------compile invalid--------------------------------------------------------------------------------------------
EXEC sys.UTL_RECOMP.recomp_serial;



---------------------------------------------------------------Analyze-----------------------------------------------------------------------------------
EXEC DBMS_STATS.gather_database_stats(degree => DBMS_STATS.DEFAULT_DEGREE);




SET HEADING OFF

spool c:\temp\invalid.sql ;
select OBJECT_NAME from dba_objects where STATUS='INVALID';

select
'ALTER ' || OBJECT_TYPE || ' ' || OWNER || '."' || OBJECT_NAME || '" COMPILE;' from dba_objects where status = 'INVALID'
and object_type in ('PACKAGE','FUNCTION','PROCEDURE','VIEW','TRIGGER');

Select decode( object_type, 'PACKAGE BODY', 'ALTER PACKAGE ' ||  OWNER || '.' || OBJECT_NAME || ' COMPILE BODY;')
from dba_objects
where status = 'INVALID' and object_type in ('PACKAGE BODY') order by object_type;

select 'ALTER ' || OWNER || ' ' || OBJECT_TYPE || ' "' || OBJECT_NAME || '" COMPILE;' from dba_objects where status = 'INVALID'
and object_type in ('SYNONYM');

Select decode( object_type, 'TYPE', 'ALTER TYPE ' ||  OWNER || '.' || OBJECT_NAME || ' COMPILE;')
from dba_objects where status = 'INVALID' and object_type in ('TYPE') order by object_type;

Select decode( object_type, 'TYPE BODY', 'ALTER TYPE ' ||  OWNER || '.' || OBJECT_NAME || ' COMPILE BODY;')
from dba_objects
where status = 'INVALID' and object_type in ('TYPE BODY') order by object_type;

spool out ;
@ c:\temp\invalid.sql ;


SELECT * FROM USER_ERRORS;


select 'SELECT INSTANCE_NAME,HOST_NAME FROM V$INSTANCE@' ||Db_Link || ';' from dba_db_links;


















-------------------------------Drop objects

BEGIN
 FOR cur_rec IN (SELECT object_name, object_type
                  FROM   user_objects where object_type='TRIGGER') LOOP
    BEGIN
      EXECUTE IMMEDIATE 'DROP ' || cur_rec.object_type || ' ' || cur_rec.object_name;
    EXCEPTION
      WHEN OTHERS THEN
        NULL;
    END;
  END LOOP;
  FOR cur_rec IN (SELECT table_name, constraint_name
                  FROM   user_constraints
                  WHERE  constraint_type = 'R') LOOP
    EXECUTE IMMEDIATE 'ALTER TABLE ' || cur_rec.table_name || ' DROP CONSTRAINT ' || cur_rec.constraint_name;
  END LOOP;
FOR cur_rec IN (SELECT object_name, object_type
                  FROM   user_objects) LOOP
    BEGIN
      EXECUTE IMMEDIATE 'DROP ' || cur_rec.object_type || ' ' || cur_rec.object_name;
    EXCEPTION
      WHEN OTHERS THEN
        NULL;
    END;
  END LOOP;
FOR cur_rec IN (SELECT owner,synonym_name,table_owner FROM  dba_synonyms where table_owner not in ('DBSNMP','ORACLE_OCM','OUTLN','SYS','SYSMAN','SYSTEM','TSMSYS','WMSYS','XDB')) LOOP
BEGIN
      EXECUTE IMMEDIATE 'DROP ' || cur_rec.owner || ' SYNONYM ' || cur_rec.table_owner || '.' || cur_rec.synonym_name || ' FORCE';
    EXCEPTION
      WHEN OTHERS THEN
        NULL;
    END;
  END LOOP;
END;
/
purge recyclebin ;





Thursday, October 18, 2012

Temporary Tablespace Related Scripts

To check instance-wise total allocated, total used TEMP for both rac and non-rac

set lines 152
col FreeSpaceGB format 999.999
col UsedSpaceGB format 999.999
col TotalSpaceGB format 999.999
col host_name format a30
col tablespace_name format a30
select tablespace_name,
(free_blocks*8)/1024/1024 FreeSpaceGB,
(used_blocks*8)/1024/1024 UsedSpaceGB,
(total_blocks*8)/1024/1024 TotalSpaceGB,
i.instance_name,i.host_name
from gv$sort_segment ss,gv$instance i where ss.tablespace_name in (select tablespace_name from dba_tablespaces where contents='TEMPORARY') and
i.inst_id=ss.inst_id;

Total Used and Total Free Blocks

select inst_id, tablespace_name, total_blocks, used_blocks, free_blocks  from gv$sort_segment;

Another Query to check TEMP USAGE

col name for a20
SELECT d.status "Status", d.tablespace_name "Name", d.contents "Type", d.extent_management
"ExtManag",
TO_CHAR(NVL(a.bytes / 1024 / 1024, 0),'99,999,990.900') "Size (M)", TO_CHAR(NVL(t.bytes,
0)/1024/1024,'99999,999.999') ||'/'||TO_CHAR(NVL(a.bytes/1024/1024, 0),'99999,999.999') "Used (M)",
TO_CHAR(NVL(t.bytes / a.bytes * 100, 0), '990.00') "Used %"
FROM sys.dba_tablespaces d, (select tablespace_name, sum(bytes) bytes from dba_temp_files group by
tablespace_name) a,
(select tablespace_name, sum(bytes_cached) bytes from
v$temp_extent_pool group by tablespace_name) t
WHERE d.tablespace_name = a.tablespace_name(+) AND d.tablespace_name = t.tablespace_name(+)
AND d.extent_management like 'LOCAL' AND d.contents like 'TEMPORARY';

Temporary Tablespace groups

SELECT * FROM DATABASE_PROPERTIES where PROPERTY_NAME='DEFAULT_TEMP_TABLESPACE';

select tablespace_name,contents from dba_tablespaces where tablespace_name like '%TEMP%';

select * from dba_tablespace_groups;

Block wise Check

select TABLESPACE_NAME, TOTAL_BLOCKS, USED_BLOCKS, MAX_USED_BLOCKS, MAX_SORT_BLOCKS, FREE_BLOCKS from V$SORT_SEGMENT;

select sum(free_blocks) from gv$sort_segment where tablespace_name = 'TEMP';
To Check Percentage Usage of Temp Tablespace

select (s.tot_used_blocks/f.total_blocks)*100 as "percent used"
from (select sum(used_blocks) tot_used_blocks
from v$sort_segment where tablespace_name='TEMP') s,
(select sum(blocks) total_blocks
from dba_temp_files where tablespace_name='TEMP') f;

To check Used Extents ,Free Extents available in Temp Tablespace

SELECT tablespace_name, extent_size, total_extents, used_extents,free_extents, max_used_size FROM v$sort_segment;

To list all tempfiles of Temp Tablespace

col file_name for a45
select tablespace_name,file_name,bytes/1024/1024,maxbytes/1024/1024,autoextensible from dba_temp_files  order by file_name;

SELECT d.tablespace_name tablespace , d.file_name filename, d.file_id fl_id, d.bytes/1024/1024
size_m
, NVL(t.bytes_cached/1024/1024, 0) used_m, TRUNC((t.bytes_cached / d.bytes) * 100) pct_used
FROM
sys.dba_temp_files d, v$temp_extent_pool t, v$tempfile v
WHERE (t.file_id (+)= d.file_id)
AND (d.file_id = v.file#);

Additional checks

select distinct(temporary_tablespace) from dba_users;

select username,default_tablespace,temporary_tablespace from dba_users order by temporary_tablespace;

SELECT * FROM DATABASE_PROPERTIES where PROPERTY_NAME='DEFAULT_TEMP_TABLESPACE';

Changing the default temporary Tablespace

SQL> alter database default temporary tablespace TEMP;

Database altered.

To add tempfile to Temp Tablespace

alter tablespace  temp  add tempfile '&tempfilepath' size 1800M;

alter tablespace temp add tempfile '/m001/oradata/SID/temp02.dbf' size 1000m;

alter tablespace TEMP add tempfile '/SID/oradata/data02/temp04.dbf' size 1800M autoextend on maxsize 1800M;

To resize the  tempfile in Temp Tablespace

alter database tempfile '/u02/oradata/TESTDB/temp01.dbf' resize 250M

alter database tempfile '/SID/oradata/data02/temp12.dbf' autoextend on maxsize 1800M;

alter tablespace TEMP add tempfile '/SID/oradata/data02/temp05.dbf' size 1800m reuse;

To find Sort Segment Usage by Users

select username,sum(extents) "Extents",sum(blocks) "Block"
from v$sort_usage
group by username;

To find Sort Segment Usage by a particular User

SELECT s.username,s.sid,s.serial#,u.tablespace, u.contents, u.extents, u.blocks
FROM v$session s, v$sort_usage u
WHERE s.saddr=u.session_addr
order by u.blocks desc;

To find Total Free space in Temp Tablespace

select 'FreeSpace  ' || (free_blocks*8)/1024/1024 ||' GB'  from v$sort_segment where tablespace_name='TEMP';

select tablespace_name , (free_blocks*8)/1024/1024  FreeSpaceInGB,
(used_blocks*8)/1024/1024  UsedSpaceInGB,
(total_blocks*8)/1024/1024  TotalSpaceInGB
from v$sort_segment where tablespace_name like '%TEMP%'

To find  Total Space Allocated for Temp Tablespace

select 'TotalSpace ' || (sum(blocks)*8)/1024/1024 ||' GB'  from dba_temp_files where tablespace_name='TEMP';

Get 10 sessions with largest temp usage

cursor bigtemp_sids is
select * from (
select s.sid,
s.status,
s.sql_hash_value sesshash,
u.SQLHASH sorthash,
s.username,
u.tablespace,
sum(u.blocks*p.value/1024/1024) mbused ,
sum(u.extents) noexts,
nvl(s.module,s.program) proginfo,
floor(last_call_et/3600)||':'||
floor(mod(last_call_et,3600)/60)||':'||
mod(mod(last_call_et,3600),60) lastcallet
from v$sort_usage u,
v$session s,
v$parameter p
where u.session_addr = s.saddr
and p.name = 'db_block_size'
group by s.sid,s.status,s.sql_hash_value,u.sqlhash,s.username,u.tablespace,
nvl(s.module,s.program),
floor(last_call_et/3600)||':'||
floor(mod(last_call_et,3600)/60)||':'||
mod(mod(last_call_et,3600),60)
order by 7 desc,3)
where rownum < 11;

Displays the amount of IO for each tempfile

SELECT SUBSTR(t.name,1,50) AS file_name,
f.phyblkrd AS blocks_read,
f.phyblkwrt AS blocks_written,
f.phyblkrd + f.phyblkwrt AS total_io
FROM   v$tempstat f,v$tempfile t
WHERE  t.file# = f.file#
ORDER BY f.phyblkrd + f.phyblkwrt DESC;

select * from (SELECT u.tablespace, s.username, s.sid, s.serial#, s.logon_time, program, u.extents, ((u.blocks*8)/1024) as MB,
i.inst_id,i.host_name
FROM gv$session s, gv$sort_usage u ,gv$instance i
WHERE s.saddr=u.session_addr and u.inst_id=i.inst_id  order by MB DESC) a where rownum<10;

Check for ORA-1652

show parameter background

cd <background dump destination>

ls -ltr|tail

view <alert log file name>

shift + G ---> to get the tail end...

?ORA-1652 ---- to search of the error...

shift + N ---- to step for next reported error...

I used these queries to check some settings:

-- List all database files and their tablespaces:
select  file_name, tablespace_name, status
,bytes   /1000000  as MB
,maxbytes/1000000  as MB_max
from dba_data_files ;

-- What temporary tablespace is each user using?:
select username, temporary_tablespace, default_tablespace from dba_users ;

-- List all tablespaces and some settings:
select tablespace_name, status, contents, extent_management
from dba_tablespaces ;

TABLESPACE_NAME                CONTENTS  EXTENT_MAN STATUS
------------------------------ --------- ---------- ---------
SYSTEM                         PERMANENT DICTIONARY ONLINE
TOOLS                          PERMANENT DICTIONARY ONLINE
TEMP                           TEMPORARY DICTIONARY OFFLINE
TMP                            TEMPORARY LOCAL      ONLINE

Now, the above query and the storage clause of the old 'create tablespace TEMP' command seem to tell us the tablespace only allows temporary objects, so it should be safe to assume that no one created any tables or other permanent objects in TEMP by mistake, as I think Oracle would prevent that. However, just to be absolutely certain, I decided to double-check. Checking for any tables in the tablespace is very easy:

-- Show number of tables in the TEMP tablespace - SHOULD be 0:
select count(*)  from dba_all_tables
where tablespace_name = 'TEMP' ;

Checking for any other objects (views, indexes, triggers, pl/sql, etc.) is trickier, but this query seems to work correctly - note that you'll probably need to connect internal in order to see the sys_objects view:

-- Shows all objects which exist in the TEMP tablespace - should get
-- NO rows for this:
column owner        format a20
column object_type  format a30
column object_name  format a40
select
o.owner  ,o.object_name
,o.object_type
from sys_objects s
,dba_objects o
,dba_data_files df
where df.file_id = s.header_file
and o.object_id = s.object_id
and df.tablespace_name = 'TEMP' ;

Identifying WHO is currently using TEMP Segments

10g onwards

SELECT sysdate,a.username, a.sid, a.serial#, a.osuser, (b.blocks*d.block_size)/1048576 MB_used, c.sql_text
FROM v$session a, v$tempseg_usage b, v$sqlarea c,
     (select block_size from dba_tablespaces where tablespace_name='TEMP') d
    WHERE b.tablespace = 'TEMP'
    and a.saddr = b.session_addr
    AND c.address= a.sql_address
    AND c.hash_value = a.sql_hash_value
    AND (b.blocks*d.block_size)/1048576 > 1024
    ORDER BY b.tablespace, 6 desc;


------------------------------------11g

select TABLESPACE_NAME , tablespace_size/1024/1024 totalMB, free_spAce/1024/1024 Just_FreeSpaceMB, (TABLESPACE_SIZE-FREE_SPACE)/1024/1024 FreeMb, (TABLESPACE_SIZE-ALLOCATED_SPACE)/1024/1024 AllocSize from dba_temp_free_space ;

SELECT TABLESPACE_NAME, FILE_ID, BYTES_USED, BYTES_FREE FROM V$TEMP_SPACE_HEADER;

DBA_TEMP_FREE_SPACE displays temporary space usage information at tablespace level.
Column Datatype NULL Description
TABLESPACE_NAME VARCHAR2(30) NOT NULL Name of the tablespace
TABLESPACE_SIZE NUMBER Total size of the tablespace, in bytes
ALLOCATED_SPACE NUMBER Total allocated space, in bytes, including space that is currently allocated and used and space that is currently allocated and available for reuse
FREE_SPACE NUMBER Total free space available, in bytes, including space that is currently allocated and available for reuse and space that is currently unallocated


Blocking Session Lockwait Best

SELECT TO_CHAR(sysdate, 'DD-MON-YYYY HH24:MI:SS')
|| ' User '
||s1.username
|| '@'
|| s1.machine
|| ' ( SID= '
|| s1.sid
|| ' ) with the statement: '
|| sqlt2.sql_text
||' is blocking the SQL statement on '
|| s2.username
|| '@'
|| s2.machine
|| ' ( SID='
|| s2.sid
|| ' ) blocked SQL -> '
||sqlt1.sql_text AS blocking_status
FROM v$lock l1, v$session s1, v$lock l2 ,
v$session s2,v$sql sqlt1, v$sql sqlt2
WHERE s1.sid =l1.sid
AND s2.sid =l2.sid AND sqlt1.sql_id= s2.sql_id AND sqlt2.sql_id= s1.prev_sql_id AND l1.BLOCK =1
AND l2.request > 0 AND l1.id1 = l2.id1 AND l2.id2 = l2.id2;

Tuesday, September 25, 2012

expdp procedure in 11g


 1) create directory export_auto as 'd:\expdp1213';

 create user dba_export_user identified by test123;

grant connect, create database link, resource, create view to dba_export_user;
grant unlimited tablespace to dba_export_user;
grant exp_full_database to dba_export_user;
grant read,write on directory export_auto to dba_export_user;
grant execute on dbms_flashback to dba_export_user;
grant create table to dba_export_user;
grant FLASHBACK ANY TABLE to dba_export_user;


2)
CREATE OR REPLACE PROCEDURE dba_export_user.start_export
IS
   hdl_job        NUMBER;
   l_cur_scn      NUMBER;
   l_job_state    VARCHAR2 (20);
   l_status       SYS.ku$_status1010;
   l_job_status   SYS.ku$_jobstatus1010;
BEGIN

 begin
    execute immediate 'drop table  dba_export_user.AUTO_EXPORT';
    exception when others then null;
   end;

   hdl_job := DBMS_DATAPUMP.OPEN ( operation => 'EXPORT', job_mode => 'FULL', job_name => 'AUTO_EXPORT' );
 
   DBMS_DATAPUMP.add_file (handle => hdl_job,filename => 'EXPDP1213.dmp',directory => 'EXPORT_AUTO',filetype => DBMS_DATAPUMP.ku$_file_type_dump_file,reusefile => 1);
                         
   DBMS_DATAPUMP.add_file (handle => hdl_job,filename => 'export.log',DIRECTORY => 'EXPORT_AUTO',filetype => DBMS_DATAPUMP.ku$_file_type_log_file,reusefile => 1);
                     
   DBMS_DATAPUMP.start_job (handle => hdl_job);
 
   DBMS_DATAPUMP.wait_for_job (handle => hdl_job, job_state => l_job_state);
 
   DBMS_OUTPUT.put_line ('Job exited with status:' || l_job_state);

  DBMS_DATAPUMP.detach(handle => hdl_job);

END;
/


3) Change the time, Date

begin
 dbms_scheduler.create_job(
      job_name => 'EXPORT_JOB'
     ,job_type => 'STORED_PROCEDURE'
     ,job_action => 'dba_export_user.start_export'
     ,start_date => '08-FEB-12 06.02.00.00 PM ASIA/CALCUTTA'
       ,repeat_interval => 'FREQ=DAILY; BYDAY=MON,TUE,WED,THU,FRI,SAT,SUN;'
     ,enabled => TRUE
     ,comments => 'EXPORT_DATABASE_JOB');
end;
/

EXEC  dbms_scheduler.run_job('EXPORT_JOB');

Friday, September 21, 2012

RMAN Block Media Recovery


From Oracle 9i onwards you can use RMAN to recover only blocks while database is up and running.
This could possibly save hours and hours of recovery time as a full database restore  is not necessary.
Error reported by user pointing to block corruption.

 POPULATE_MACSDATA - ORA-01578: ORACLE data block corrupted  (file # 48, block # 142713)
ORA-01110: data file 48: '/hqlinux08db06/ORACLE/macsl/MACSDAT_2006_06.dbf'
ORA-02063: preceding 2 lines from MODSL_MACSL_LINK
File name : /hqlinux08db06/ORACLE/macsl/MACSDAT_2006_06.dbf

Check first if the there is only one(few) blocks corrupted or most of the blocks are corrupted.

macsl:/opt/oracle/admin/macsl/bdump>
Issue command below at UNIX prompt.

dbv file=/hqlinux08db06/ORACLE/macsl/MACSDAT_2006_06.dbf BLOCKSIZE=8192 LOGFILE=test.log

DBV-00200: Block, dba 201469305, already marked corrupted

SQL> Select * from v$database_block_corruption;

You will get block number corrupt.
Ex: block 142713.

After that LOGIN TO RMAN.

rman target / catalog rman10/rman10@rman10p
RMAN> BLOCKRECOVER DATAFILE 48 BLOCK 142713;

V$database_block_corruption is the view to check the list of corrupted blocks.

If you have multiple block list as corrupt, You can use single command to recover them.

RMAN> BLOCKRECOVER corruption list;

Thursday, September 20, 2012

Table level Recovery using Flashback Table



---------------------------------------------------Recover Dropped Table from Recyclebin using Flashback Table-------------------------

Oracle Flashback Table enables you to restore a table to its state as of a previous point in time. It provides a fast, online solution for recovering a table that has been accidentally modified or deleted by a user or application. In many

cases, Oracle Flashback Table eliminates the need for you to perform more complicated point-in-time recovery operations.

Oracle Flashback Table:

Restores all data in a specified table to a previous point in time described by a timestamp or SCN.

Performs the restore operation online.

Automatically maintains all of the table attributes, such as indexes, triggers, and constraints that are necessary for an application to function with the flashed-back table.

Maintains any remote state in a distributed environment. For example, all of the table modifications required by replication if a replicated table is flashed back.

Maintains data integrity as specified by constraints. Tables are flashed back provided none of the table constraints are violated. This includes any referential integrity constraints specified between a table included in the FLASHBACK

TABLE statement and another table that is not included in the FLASHBACK TABLE statement.

Even after a flashback operation, the data in the original table is not lost. You can later revert to the original state.

FLASHBACK TABLE <table_name> TO BEFORE DROP;

Some other variations of the flashback database command include.

FLASHBACK DATABASE TO TIMESTAMP my_date;
FLASHBACK DATABASE TO BEFORE TIMESTAMP my_date;
FLASHBACK DATABASE TO SCN my_scn;
FLASHBACK DATABASE TO BEFORE SCN my_scn;

--------------------------------------------------Recover deleted Table Data from Recyclebin using Flashback Table---------------------

On Oracle Database 11g (10gR2...), we can rewind one or more tables back to their contents at a previous time without affecting other database objects.

Before we use Flashback Table, We must enable row movement on the table. because rowids will change after the flashback.

Example: Flashback the table back to previous time using SCN


select count(*) from LDBO.test;
COUNT(*)
----------
68781

SQL> SELECT CURRENT_SCN FROM V$DATABASE;

CURRENT_SCN
-----------
1584494

SQL> delete from LDBO.test where rownum <= 50000;

50000 rows deleted.

SQL> commit;

Commit complete.

SQL> select count(*) from LDBO.test;

COUNT(*)
----------
18781

SQL> SELECT CURRENT_SCN FROM V$DATABASE;

CURRENT_SCN
-----------
1587106

Enable row movement:

SQL> alter table LDBO.test enable row movement;

Table altered.

SQL> FLASHBACK TABLE LDBO.test to scn 1584494;

Flashback complete.

SQL> select count(*) from LDBO.test;


QL> alter table LDBO.test disable row movement;

Table altered.


We can rewind the table back to previous time using timestamp:

SQL> alter session set nls_date_format='YYYY/MM/DD HH24:MI:SS';

Session altered.

SQL> select sysdate from dual;

SYSDATE
-------------------
2009/08/30 17:01:09

SQL> delete from LDBO.test ;

68781 rows deleted.

SQL> commit;

Commit complete.

SQL> select sysdate from dual;

SYSDATE
-------------------
2009/08/30 17:03:18

SQL> select count(*) from LDBO.test;

COUNT(*)
----------
0

SQL> alter table LDBO.test enable row movement;

Table altered.

SQL> flashback table LDBO.test to timestamp TO_TIMESTAMP('2009/08/30 17:01:09','YYYY/MM/DD HH24:MI:SS');

Flashback complete.

SQL> select count(*) from LDBO.test;

COUNT(*)
----------
68781

--------------------------------------------------------------------------------------------Flashback Table recover table to different table----------------------

FLASHBACK TABLE test TO BEFORE DROP RENAME TO test2;

flashback table LDBO.test to timestamp TO_TIMESTAMP('2009/08/30 17:01:09','YYYY/MM/DD HH24:MI:SS') RENAME TO test2;




Friday, September 14, 2012

11g Active Data Guard - enabling Real-Time Query


Active Data Guard is a good new feature in 11g (although requires a license) which enables us to query the Standby database while redo logs are being applied to it. In earlier releases, we had to stop the log apply, open the database in read only mode and then start the log apply again when the database was taken out of the read only mode.
With Oracle 11g Active Data Guard, we can make use of our standby site to offload reporting and query type applications while at the same time not compromising on the high availability aspect.
How do we enable Active Data Guard?
If we are not using the Data Guard Broker, we need to open the standby database, set it in read only mode and then start the managed recovery as shown below.
SQL> shutdown immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> startup
ORACLE instance started.
Total System Global Area 1069252608 bytes
Fixed Size 2154936 bytes
Variable Size 847257160 bytes
Database Buffers 213909504 bytes
Redo Buffers 5931008 bytes
Database mounted.
Database opened.
SQL> recover managed standby database using current logfile disconnect;
Media recovery complete.
If we are using the Data Guard Broker CLI, DGMGRL, the procedure is a bit different and is not very clearly explained in the documentation.
You need to stop redo apply first via the SET STATE dgmgrl command, then from a SQL*PLUS session, open the database in read only mode, and then back again from dgmgrl via set SET STATE command, start the redo apply again.
Stop redo apply with the following command from Data Guard Broker CLI
DGMGRL> EDIT DATABASE ‘PRODDB’ SET STATE=’APPLY-OFF’;
Open standby read-only via SQL*Plus
SQL> alter database open read only;
Restart redo apply via broker CLI
DGMGRL> EDIT DATABASE ‘PRODDB’ SET STATE=’APPLY-ON’;
I tried to run the same only via DGMGRL and got this error:
DGMGRL> edit database PRODDB set state=”APPLY-OFF”;
Succeeded.
DGMGRL> edit database PRODDB set state=”READ ONLY”;
Error: ORA-16516: current state is invalid for the attempted operation
After we have enabled the Real-Time Query feature, we can confirm the same via the DGMGRL command – SHOW DATABASE
DGMGRL> show database verbose PRODDB_DR
Database – PRODDB_DR
Role: PHYSICAL STANDBY
Intended State: APPLY-ON
Transport Lag: 0 seconds
Apply Lag: 0 seconds
Real Time Query: ON
Note:
Even though we have enabled Real-Time Query feature, if we go to Data Guard page via the Enterprise Manager Grid Control GUI, it will show that Real-Time Query is in a Disabled state.
This is apparently a bug which applies to OEM Grid Control 10.2.0.1 to 10.2.0.5 with a 11.2 target database.
Bug 7633734: DG ADMIN PAGE REAL TIME QUERY SHOWS DISABLED WHEN ENABLED FOR 11.2 DATABASES

Followers