Posts

Problems in: FETCH FIRST n PERCENT ROWS ONLY

Wanting to count how many rows in emp table SQL> SELECT COUNT (*) FROM emp; COUNT(*) ---------- 100 Cool... now let me see how much is 5 percent of emp SQL> SELECT COUNT (*) FROM emp 2 FETCH FIRST 5 PERCENT ROWS ONLY; COUNT(*) ---------- 100 Mmmmm.... it can't be also 100 ... somthing is wierd .. Let's try other way SQL> SELECT COUNT (*) 2 FROM ( SELECT empno 3 FROM emp 4 FETCH FIRST 5 PERCENT ROWS ONLY); COUNT(*) ---------- 5 Cool, now it is working :) Now let's try in PL/SQL SQL> DECLARE 2 l_Percent_to_fetch PLS_INTEGER; 3 l_cnt PLS_INTEGER; 4 BEGIN 5 SELECT COUNT (*) 6 INTO l_cnt 7 FROM ( SELECT empno 8 FROM emp 9 FETCH FIRST l_Percent_to_fetch PERCENT ROWS ONLY); 10 END; 11 / DECLARE * ERROR at line 1: ORA-03113: end-of-file on communication channel ...

Export in Pl/Sql via DBMS_DATAPUMP

Image
CREATE OR REPLACE PACKAGE maintenance AS    PROCEDURE export_myschema;    PROCEDURE stop_job (job_name VARCHAR2, schema_name VARCHAR2);    PROCEDURE stop_all_jobs;    PROCEDURE import_schema (file_name VARCHAR2); END maintenance; /  CREATE OR REPLACE PACKAGE BODY maintenance AS    PROCEDURE export_myschema    AS       handle        NUMBER;       file_name     VARCHAR2 (200);       log_name      VARCHAR2 (200);       JOBNAME       VARCHAR2 (200);       file_prefix   VARCHAR2 (30);       dir_name      VARCHAR2 (4000);       l_fexists BOOLEAN;   ...

Undelete Files in Linux

Image
Usually I take care for backups, but the first time I tempted to neglect this habit - I just have met Morphy's law :( Fortunately there is a solution: yum install testdisk OR apt-get install testdisk To recover files simply type: photorec and follow the instructions So simple :)

Format scripts in awk, csh, ksh, perl, sh

Image
I am used to relay on tools for formatting and indenting SQL or PL/SQL code. Looking for the same for linux scripts (especially bash) I found the following code fmt.script #!/usr/bin/env perl # fmt.script - format scripts in awk, csh, ksh, perl, sh # # we do: # standardize indentation (an indent is one tab by default) # strip trailing whitespace # change ${var} to $var where possible # change ">x" to "> x" for shell scripts # change "[ ... ]" to "test ..." for Bourne shell scripts # # we may do someday, but these are harder: # convert $VAR to $var unless a setenv or default environment variable # possibly prepending stuff from template.sh # "if ... \nthen", for ... in\ndo", "while/until ... \ndo", "fn()\n{" # # to have fmt.script reformat itself (a fair test, yes?) try: # fmt.script fmt.script fmt.script.new # use tabs for indents # fmt.script -s4 fmt.script fmt.script.new # in...

Sending Mail from the database

Image
You should have an outgoing SMTP server IP to configure sending mail from the database. I already put it in the database server /etc/hosts as mailhost sqlplus / as sysdba @?/rdbms/admin/utlmail.sql @?/rdbms/admin/prvtmail.plb grant execute on UTL_MAIL to public; ALTER SYSTEM SET smtp_out_server = 'mailhost' scope=both; a simple example BEGIN UTL_MAIL.send(sender => 'Yossi@NixonIT.com', recipients => 'you@address.com', subject => 'Test Mail', message => 'Hello World', mime_type => 'text; charset=us-ascii'); END; / For further advanced options such as attachments see in this wiki

Data Pump, the unix command line

Image
Data Pump import as sysdba and several indexes, the unix way .... impdp "'sys/dba as sysdba'" schemas=SCOTT INCLUDE=INDEX:\"in \(\'PK_DEPT\',\'EMPIDX\'\)\" directory=TMP_DIR dumpfile=scott.dmp job_name=importing_scott.log

All about ORA-600 lookup tool

Image
ORA-600/ORA-7445 are generic internal error numbers for Oracle program exceptions. Sometimes these errors are unique for your specific problem and cannot be found via search engines. Using "ORA-600 lookup tool" may point your specific problem, faster and accurate. The tool can be found in ORA-600 lookup tool - Metalink Document ID 153788.1 The flowing video will guide you the usage of the LookUp Tool (11:12) - Metalink Document ID 1082674.1

List of installed Database Patches

Image
Looking for installed patches on the database I have always used opatch lsinventory (since 9.2 and up) From CPUJan2006 onwards you can just query select * from registry$history; See Metalink Note:352783.1 for more information.

oracle 11.2 on ubuntu

installing or upgrading on Ubuntu is not supported but can be done thanks to other bloggers it is well documented here https://lostinmac.com/2012/01/29/installtion-doracle-11gr2-sur-ubunutu-11-10/ thanks

Changing database options

before oracle 11.2 we should have do this steps: cd $ORACLE_HOME/rdbms/lib make -f ins_rdbms.mk dv_off cd $ORACLE_HOME/bin relink all from now this is simpler and shorter cd %ORACLE_HOME%/bin chopt disable dv All options are written in the usage syntax: usage: chopt [enable|disable] {option} options: dm = Oracle Data Mining RDBMS Files dv = Oracle Database Vault option lbac = Oracle Label Security olap = Oracle OLAP partitioning = Oracle Partitioning rat = Oracle Real Application Testing

ADRCI & Alert file

Image
ADRCI & alert file In Oracle version 11, no need to look for the location of alert log file, just use: adrci exec="set home orcl ;show alert -tail -f" detailed practical usage can be found here

Block Recovery using RMAN – on Oracle 11g

The purpose of this article is to simulate a block level corruption using BBED utility (block browser and editor) and recover using RMAN. In this situation the data file remains online throughout the recovery operation and hence other segments within the tablespace remain accessible. Since BBED exists from Oracle7 to Oracle10g, we will have to copy some files from earlier version and compile it Cp $ORA10g_HOME/rdbms/lib/ssbbded.o $ORA11g_HOME/rdbms/lib Cp $ORA10g_HOME/rdbms/lib/sbbdpt.o $ORA11g_HOME/rdbms/lib Message files (list may differ): Cp $ORA10g_HOME/rdbms/mesg/bbedus.msb $ORA11g_HOME/rdbms/mesg Cp $ORA10g_HOME/rdbms/mesg/bbedus.msg $ORA11g_HOME/rdbms/mesg Cp $ORA10g_HOME/rdbms/mesg/bbedar.msb $ORA11g_HOME/rdbms/mesg Issue the following command: make -f $ORA11g_HOME/rdbms/lib/ins_rdbms.mk BBED=$ORACLE_HOME/bin/bbed $ORACLE_HOME/bin/bbed $ORA11g_HOME/bin/bbed password: blockedit SQL> Set pages 0 SQL> set feedback off SQL> spool fileunix.log SQL> select fi...

reliable replacement for "ps -ef"

On linux redhat 5 I checked the command ps -ef in a loop and found out that it is not reliable. checked this way: while [ `ps -ef |grep tnslsnr | grep -v grep | wc -l` -eq 1 ]; do printf . ; done after about of 2 minutes the loop finished since it didn't find the process. looking for something more trusted I found the command pgrep checked this way: while [ `pgrep tnslsnr 1>/dev/null; echo $?` -ne 1 ]; do printf . ; done and it is still running in a loop .... ;) and no need to use awk or grep -v here are some commands and the behavior of pgrep : # pgrep smon # pgrep -f smon 2396 2533 # pgrep -fl smon 2396 ora_smon_orcl 2533 ora_smon_mydb # pgrep -fl ora_smon_orcl 2396 ora_smon_orcl # echo $? 0 # pgrep not_exist_process # echo $? 1 There are some more parameters, check: man pgrep

Filename validation Using Regular Expression

Extract the filename from a full file path unix select substr(file_name,(instr(file_name,'/',-1,1)+1),length(file_name)) FROM dba_data_files; windows select substr(file_name,(instr(file_name,'\',-1,1)+1),length(file_name)) FROM dba_data_files; Validates a long filename using Windows' rules: select file_name from table_of_files WHERE not REGEXP_LIKE(file_name,'^[^\\\./:\*\?\" \|]{1}[^\\/:\*\?\" \|]{0,254}$'); combinning these two SQLs: WITH files AS ( select substr(file_name,(instr(file_name,'/',-1,1)+1),length(file_name)) base_filename FROM dba_data_files) select base_filename from files WHERE REGEXP_LIKE(base_filename,'^[^\\\./:\*\?\" \|]{1}[^\\/:\*\?\" \|]{0,254}$');

Valid values for init.ora parameters

A new option started from 11.1 for listing Valid Values in init.ora at the site of Jonathan Lewis http://jonathanlewis.wordpress.com/2011/03/08/valid-values/

Israeli Identity Card Valiadation

Needed to check the validity of an Israeli identity card number I created this simple function CREATE OR REPLACE FUNCTION checkid (id_number IN VARCHAR2) RETURN VARCHAR2 IS fixed_number VARCHAR2 (10); digit NUMBER := 0; sum_digits NUMBER := 0; BEGIN CASE WHEN LENGTH (id_number) 9 THEN RETURN 'Too Long'; ELSE fixed_number := id_number; END CASE; FOR i IN 1 .. 9 LOOP digit := TO_NUMBER (SUBSTR (fixed_number, i, 1)) * (CASE WHEN MOD (i, 2) = 0 THEN 2 ELSE 1 END); IF LENGTH (digit) > 1 THEN digit := SUBSTR (digit, 1, 1) + SUBSTR (digit, 2, 1); END IF; DBMS_OUTPUT.put_line (i || '#'); sum_digits := sum_digits + digit; IF MOD (sum_digits, 10) = 0 THEN RETURN 'OK'; ELSE RETURN 'BAD'; END IF; END LOOP; RETURN TO_CHAR (sum_digits); END; / references: http://goo.gl/z2roI http://goo.gl/dCbS0

impdp appending data with query

Trying to retrieve lost records from a datapump backup directly to the production database using impdp syntax: impdp User/password directory=my_directory dumpfile=my_full_backup.dmp logfile=imp_lost_records.log QUERY=MY_TABLE:\"where code=1 and recid in \(2,5,8\) \" job_name=imp_lost_records INCLUDE=TABLE:\"=\'MY_TABLE\'\" CONTENT=DATA_ONLY TABLE_EXISTS_ACTION=APPEND

Methods for viewing SQL Execution Plans

Using Autotrace SQL> set autotrace traceonly explain SQL> select ename from emp where sal > 500; Execution Plan ---------------------------------------------------------- Plan hash value: 2872589290 ------------------------------------------------------------------------- | Id | Operation | Name | Rows | Bytes |Cost (%CPU)| Time | ------------------------------------------------------------------------- | 0 | SELECT STATEMENT | | 1 | 25 | 2 (0)| 00:00:01 | |* 1 | TABLE ACCESS FULL| EMP | 1 | 25 | 2 (0)| 00:00:01 | ------------------------------------------------------------------------- Using DBMS_XPLAN Package SQL> explain plan for select ename from emp where sal > 500; Explained. SQL> select * from TABLE(dbms_xplan.display); PLAN_TABLE_OUTPUT ------------------------------ Plan hash value: 2872589290 ------------------------------------------------------------------------- |...

Loggon Trigger for Tracing

Using the same technique I mentioned at " Tracing Commands " here is a code in a form of logging trigger, easier when you want to capture just a specific schema from the very first transaction. CREATE OR REPLACE TRIGGER SYS. LOGON_TRACE_CRYSTAL_TRG AFTER LOGON ON CRYSTAL. SCHEMA DECLARE cmd VARCHAR2(100); BEGIN cmd := 'ALTER SESSION SET max_dump_file_size = unlimited'; EXECUTE IMMEDIATE cmd; cmd := 'ALTER SESSION SET tracefile_identifier = ''10046'''; EXECUTE IMMEDIATE cmd; cmd := 'ALTER SESSION SET statistics_level = ALL'; EXECUTE IMMEDIATE cmd; cmd := 'ALTER SESSION SET events ''10046 trace name context forever, level 12'''; EXECUTE IMMEDIATE cmd; EXCEPTION WHEN OTHERS THEN --NULL; RAISE; END ; / optional: CREATE OR REPLACE TRIGGER  SYS. LOGOFF_TRACE_CRYSTAL_TRG BEFORE LOGOFF ON CRYSTAL. SCHEMA DECLARE cmd VARCHAR2(100); BEGIN cmd := 'ALTER SESSION SET EVENTS ''10046...

Format Shell Scripts

Cool and simple code to format any kind of script in Unix environment awk.info » Format Shell Scripts Recommended