Wednesday, 12 September 2012

Procedures


Stored Procedures
What is a Stored Procedure?
A stored procedure or in simple a proc is a named PL/SQL block which performs one or more specific task. This is similar to a procedure in other programming languages. A procedure has a header and a body. The header consists of the name of the procedure and the parameters or variables passed to the procedure. The body consists or declaration section, execution section and exception section similar to a general PL/SQL Block. A procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.
We can pass parameters to procedures in three ways. 
1) IN-parameters
2) OUT-parameters
3) IN OUT-parameters
A procedure may or may not return any value.
General Syntax to create a procedure is:
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]
IS   
   Declaration section
BEGIN   
   Execution section
EXCEPTION   
  Exception section
END;
IS - marks the beginning of the body of the procedure and is similar to DECLARE in anonymous PL/SQL Blocks. The code between IS and BEGIN forms the Declaration section.
The syntax within the brackets [ ] indicate they are optional. By using CREATE OR REPLACE together the procedure is created if no other procedure with the same name exists or the existing procedure is replaced with the current code.
The below example creates a procedure ‘employer_details’ which gives the details of the employee.
 CREATE OR REPLACE PROCEDURE employer_details
               IS
                               CURSOR emp_cur IS
                               SELECT first_name, last_name, salary FROM emp_tbl;
                                emp_rec emp_cur%rowtype;
               BEGIN
                               FOR emp_rec in sales_cur
                               LOOP
                               dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
                                                                                                            || ' ' ||emp_cur.salary);
                               END LOOP;
               END;
 /

Parameters in Procedure and Functions

How to pass parameters to Procedures and Functions in PL/SQL ?
In PL/SQL, we can pass parameters to procedures and functions in three ways.
1) IN type parameter: These types of parameters are used to send values to stored procedures.
2) OUT type parameter: These types of parameters are used to get values from stored procedures. This is similar to a return type in functions.
3) IN OUT parameter: These types of parameters are used to send values and get values from stored procedures.
NOTE: If a parameter is not explicitly defined a parameter type, then by default it is an IN type parameter.
1) IN parameter:
This is similar to passing parameters in programming languages. We can pass values to the stored procedure through these parameters or variables. This type of parameter is a read only parameter. We can assign the value of IN type parameter to a variable or use it in a query, but we cannot change its value inside the procedure.
The General syntax to pass a IN parameter is
CREATE [OR REPLACE] PROCEDURE procedure_name (
  param_name1 IN datatype, param_name12 IN datatype ... )
  • param_name1, param_name2... are unique parameter names.
  • datatype - defines the datatype of the variable.
  • IN - is optional, by default it is a IN type parameter.

2) OUT Parameter:
The OUT parameters are used to send the OUTPUT from a procedure or a function. This is a write-only parameter i.e, we cannot pass values to OUT paramters while executing the stored procedure, but we can assign values to OUT parameter inside the stored procedure and the calling program can recieve this output value.
The General syntax to create an OUT parameter is
CREATE [OR REPLACE] PROCEDURE proc2 (param_name OUT datatype)
The parameter should be explicity declared as OUT parameter.

3) IN OUT Parameter:
The IN OUT parameter allows us to pass values into a procedure and get output values from the procedure. This parameter is used if the value of the IN parameter can be changed in the calling program.
By using IN OUT parameter we can pass values into a parameter and return a value to the calling program using the same parameter. But this is possible only if the value passed to the procedure and output value have a same datatype. This parameter is used if the value of the parameter will be changed in the procedure.
The General syntax to create an IN OUT parameter is
CREATE [OR REPLACE] PROCEDURE proc3 (param_name IN OUT datatype)


The below examples show how to create stored procedures using the above three types of parameters.
Example1:
Using IN and OUT parameter:
Let’s create a procedure which gets the name of the employee when the employee id is passed.
 CREATE OR REPLACE PROCEDURE emp_name (id IN NUMBER, emp_name OUT NUMBER)
 IS
 BEGIN
    SELECT first_name INTO emp_name
    FROM emp_tbl WHERE empID = id;
 END;
 /
We can call the procedure ‘emp_name’ in this way from a PL/SQL Block.
 DECLARE
  empName varchar(20);
  CURSOR id_cur SELECT id FROM emp_ids;
 BEGIN
 FOR emp_rec in id_cur
 LOOP
   emp_name(emp_rec.id, empName);
   dbms_output.putline('The employee ' || empName || ' has id ' || emp-rec.id);
 END LOOP;
 END;
 /
In the above PL/SQL Block
In line no 3; we are creating a cursor ‘id_cur’ which contains the employee id.
In line no 7; we are calling the procedure ‘emp_name’, we are passing the ‘id’ as IN parameter and ‘empName’ as OUT parameter.
In line no 8; we are displaying the id and the employee name which we got from the procedure ‘emp_name’.
Example 2:
Using IN OUT parameter in procedures:
 CREATE OR REPLACE PROCEDURE emp_salary_increase
 (emp_id IN emptbl.empID%type, salary_inc IN OUT emptbl.salary%type)
 IS
    tmp_sal number;
 BEGIN
    SELECT salary
    INTO tmp_sal
    FROM emp_tbl
   WHERE empID = emp_id;
   IF tmp_sal between 10000 and 20000 THEN
      salary_inout := tmp_sal * 1.2;
   ELSIF tmp_sal between 20000 and 30000 THEN
      salary_inout := tmp_sal * 1.3;
   ELSIF tmp_sal > 30000 THEN
      salary_inout := tmp_sal * 1.4;
   END IF;
 END;
 /
The below PL/SQL block shows how to execute the above 'emp_salary_increase' procedure.
 DECLARE
    CURSOR updated_sal is
    SELECT empID,salary
    FROM emp_tbl;
    pre_sal number;
 BEGIN
   FOR emp_rec IN updated_sal LOOP
     pre_sal := emp_rec.salary;
       emp_salary_increase(emp_rec.empID, emp_rec.salary);
       dbms_output.put_line('The salary of ' || emp_rec.empID ||
                ' increased from '|| pre_sal || ' to '||emp_rec.salary);
   END LOOP;
 END;
/
How to execute a Stored Procedure?
There are two ways to execute a procedure.
1) From the SQL prompt.
 EXECUTE [or EXEC] procedure_name;
2) Within another procedure – simply use the procedure name.
  procedure_name;
NOTE: In the examples given above, we are using backward slash ‘/’ at the end of the program. This indicates the oracle engine that the PL/SQL program has ended and it can begin processing the statements.

Parameter Data types

The datatype of a formal parameter consists of one of the following:
·         An unconstrained type name, such as NUMBER or VARCHAR2.
·         A type that is constrained using the %TYPE or %ROWTYPE attributes.
Note:
Numerically constrained types such as NUMBER(2) or VARCHAR2(20) are not allowed in a parameter list.
%TYPE and %ROWTYPE Attributes
Use the type attributes %TYPE and %ROWTYPE to constrain the parameter. For example, the Get_emp_names procedure specification in"Parameters for Procedures and Functions" could be written as the following:
PROCEDURE Get_emp_names(Dept_num IN Emp_tab.Deptno%TYPE)
 
This has the Dept_num parameter take the same datatype as the Deptno column in the Emp_tab table. The column and table must be available when a declaration using %TYPE (or %ROWTYPE) is elaborated.
Using %TYPE is recommended, because if the type of the column in the table changes, then it is not necessary to change the application code.
If the Get_emp_names procedure is part of a package, then you can use previously-declared public (package) variables to constrain a parameter datatype. For example:
Dept_number    number(2);
...
PROCEDURE Get_emp_names(Dept_num IN Dept_number%TYPE);
 
Use the %ROWTYPE attribute to create a record that contains all the columns of the specified table. The following example defines theGet_emp_rec procedure, which returns all the columns of the Emp_tab table in a PL/SQL record for the given empno:
Caution:
To execute the following, use CREATE OR REPLACE PROCEDURE...
PROCEDURE Get_emp_rec (Emp_number  IN  Emp_tab.Empno%TYPE,
                       Emp_ret     OUT Emp_tab%ROWTYPE) IS
BEGIN
   SELECT Empno, Ename, Job, Mgr, Hiredate, Sal, Comm, Deptno
      INTO Emp_ret
      FROM Emp_tab
      WHERE Empno = Emp_number;
END;
 
You could call this procedure from a PL/SQL block as follows:
DECLARE
   Emp_row      Emp_tab%ROWTYPE;     -- declare a record matching a
                                     -- row in the Emp_tab table
BEGIN
   Get_emp_rec(7499, Emp_row);   -- call for Emp_tab# 7499
   DBMS_OUTPUT.PUT(Emp_row.Ename || ' '                || Emp_row.Empno);
   DBMS_OUTPUT.PUT(' '           || Emp_row.Job || ' ' || Emp_row.Mgr);
   DBMS_OUTPUT.PUT(' '           || Emp_row.Hiredate   || ' ' || Emp_row.Sal);
   DBMS_OUTPUT.PUT(' '           || Emp_row.Comm || ' '|| Emp_row.Deptno);
   DBMS_OUTPUT.NEW_LINE;
END;
 
Stored functions can also return values that are declared using %ROWTYPE. For example:
FUNCTION Get_emp_rec (Dept_num IN Emp_tab.Deptno%TYPE)
   RETURN Emp_tab%ROWTYPE IS ...
Tables and Records
You can pass PL/SQL tables as parameters to stored procedures and functions. You can also pass tables of records as parameters.
Note:
When passing a user defined type, such as a PL/SQL table or record to a remote procedure, to make PL/SQL use the same definition so that the type checker can verify the source, you must create a redundant loop back DBLINK so that when the PL/SQL compiles, both sources pull from the same location.
Default Parameter Values
Parameters can take default values. Use the DEFAULT keyword or the assignment operator to give a parameter a default value. For example, the specification for the Get_emp_names procedure could be written as the following:
PROCEDURE Get_emp_names (Dept_num IN NUMBER DEFAULT 20) IS ...
 
or
PROCEDURE Get_emp_names (Dept_num IN NUMBER := 20) IS ...
 
When a parameter takes a default value, it can be omitted from the actual parameter list when you call the procedure. When you do specify the parameter value on the call, it overrides the default value.
Note:
Unlike in an anonymous PL/SQL block, you do not use the keyword DECLARE before the declarations of variables, cursors, and exceptions in a stored procedure. In fact, it is an error to use it.

Creating Stored Procedures and Functions

Use a text editor to write the procedure or function. At the beginning of the procedure, place the following statement:
CREATE PROCEDURE Procedure_name AS   ...
 
For example, to use the example in "%TYPE and %ROWTYPE Attributes ", create a text (source) file called get_emp.sql containing the following code:
CREATE PROCEDURE Get_emp_rec (Emp_number  IN  Emp_tab.Empno%TYPE,
                              Emp_ret     OUT Emp_tab%ROWTYPE) AS
BEGIN
   SELECT Empno, Ename, Job, Mgr, Hiredate, Sal, Comm, Deptno
      INTO Emp_ret
      FROM Emp_tab
      WHERE Empno = Emp_number;
END;
/
 
Then, using an interactive tool such as SQL*Plus, load the text file containing the procedure by entering the following statement:
SQL> @get_emp
 
This loads the procedure into the current schema from the get_emp.sql file (.sql is the default file extension). Note the slash (/) at the end of the code. This is not part of the code; it just activates the loading of the procedure.
Use the CREATE [OR REPLACE] FUNCTION... statement to store functions.
Caution:
When developing a new procedure, it is usually much more convenient to use the CREATE OR REPLACE PROCEDURE statement. This replaces any previous version of that procedure in the same schema with the newer version, but note that this is done without warning.
You can use either the keyword IS or AS after the procedure parameter list.
Altering Stored Procedures and Functions
To alter a stored procedure or function, you must first drop it using the DROP PROCEDURE or DROP FUNCTION statement, then re-create it using the CREATE PROCEDURE or CREATE FUNCTION statement. Alternatively, use the CREATE OR REPLACE PROCEDURE or CREATE ORREPLACE FUNCTION statement, which first drops the procedure or function if it exists, then re-creates it as specified.
Caution:
The procedure or function is dropped without any warning.

Dropping Procedures and Functions

A standalone procedure, a standalone function, a package body, or an entire package can be dropped using the SQL statements 
DROPPROCEDURE, DROP FUNCTION, DROP PACKAGE BODY, and DROP PACKAGE, respectively.
A DROP PACKAGE statement drops both the specification and body of a package.
The following statement drops the Old_sal_raise procedure in your schema:
DROP PROCEDURE Old_sal_raise;

Thursday, 30 August 2012

Basic UNIX Commands Continue..




Compress command.
Compress command compresses a file and returns the original file with .z extension, to uncompress this filename.Z file use 
uncompress filename command. syntax for compress command is
compress options files
Options
  • -bn limit the number of bits in coding to n.
  • -c write to standard output (do not change files).
  • -f compress conditionally, do not prompt before overwriting files.
  • -v Print the resulting percentage of reduction for files.


Uncompress command.
Uncompress file uncompresses a file and return it to its original form.
syntax is
uncompress filename.Z this uncompresses the compressed file to its original name.
Options
  • -c write to standard output without changing files


Cpio command.
cpio command is useful to backup the file systems. It copy file archives in from or out to tape or disk, or to another location on the local machine. Its syntax is
cpio flags [options]
It has three flags, -i, -o, -p
  • cpio -i [options] [patterns]
    • cpio -i copy in files who names match selected patterns.
    • If no pattern is used all files are copied in.
    • It is used to write to a tape.
cpio -o
    • Copy out a list of files whose name are given on standard output.
cpio -p
    • copy files to another directory on the same system.
Options
    • -a reset access times of input files.
    • -A append files to an archive (must use with -o).
    • -b swap bytes and half-words. Words are 4 bytes.
    • -B block input or output using 5120 bytes per record.
    • -c Read or write header information as Ascii character.
    • -d create directories as needed.
    • -l link files instead of copying.
    • -o file direct output to a file.
    • -r rename files interactively.
    • -R ID reassign file ownership and group information to the user's login ID.
    • -V print a dot for each file read or written.
    • -s swap bytes.
    • -S swap half bytes.
    • -v print a list of filenames.
Examples
    • find . -name "*.old" -print | cpio -ocvB > /dev/rst8 will backup all *.old files to a tape in /dev/rst8
    • cpio -icdv "save"" < /dev/rst8 will restore all files whose name contain "save"
    • find . -depth -print | cpio -padm /mydir will move a directory tree.


Dump command is useful to backup the file systems.
dump command copies all the files in filesystem that have been changed after a certain date. It is good for incremental backups. This information about date is derived from /var/adm/dumpdates and /etc/fstab .
syntax for HP-UX dump is
/usr/sbin/dump [option [argument ...] filesystem] 
Options
  • 0-9 This number is dump level. 0 option causes entire filesystem to be dumped.
  • b blocking factor taken into argument.
  • d density of tape default value is 1600.
  • f place the dump on next argument file instead of tape.
  • This example causes the entire file system (/mnt) to be dumped on /dev/rmt/c0t0d0BEST and specifies that the density of the tape is 6250 BPI.
    • /usr/sbin/dump 0df 6250 /dev/rmt/c0t0d0BEST /mnt
  • for more info type man dump at command line.


Pack command.
pack command compacts each file and combine them together into a filename.z file. The original file is replaced. Pcat and unpack will restore packed files to their original form.
Syntax is
Pack options files 
Options
  • - Print number of times each byte is used, relative frequency and byte code.
  • -f Force the pack even when disk space isn't saved.
  • To display Packed files in a file use pcat command
    pcat filename.z
  • To unpack a packed file use unpack command as unpack filename.z .


Tar command.
tar command creates an archive of files into a single file.
Tar copies and restore files to a tape or any storage media. Synopsis of tar is
tar [options] [file]

Examples:
tar cvf /dev/rmt/0 /bin /usr/bin creates an archive of /bin and /usr/bin, and store on the tape in /dev/rmt0.
tar tvf /dev/rmt0 will list the tape's content in a /dev/rmt0 drive.
tar cvf - 'find . -print' > backup.tar will creates an archive of current directory and store it in file backup.tar.
Functions:
  • c creates a new tape.
  • r append files to a tape.
  • t print the names of files if they are stored on the tape.
  • x extract files from tape.
Options:
  • b n use blocking factor of n.
  • l print error messages about links not found.
  • L follow symbolic links.
  • v print function letter (x for extraction or a for archive) and name of files.




Mt command
Mt command is used for tape and other device functions like rewinding, ejecting, etc. It give commands to tape device rather than tape itself. Mt command is BSD command and is seldom found in system V unix versions.
syntax is
mt [-t tapename] command [count] 
mt for HP-UX accept following commands
  • eof write count EOF marks.
  • fsf Forward space count files.
  • fsr Forward space count records.
  • bsf Backward space count files.
  • bsr Backward space count records.
  • rew Rewind tape.
  • offl Rewind tape and go offline.
  • eod Seek to end of data (DDS and QIC drives only).
  • smk Write count setmarks (DDS drives only).
  • fss Forward space count setmarks (DDS drives only).
  • bss Backward space count setmarks (DDS drives only).
  • Examples
    • mt -t /dev/rmt/0mnb rew will rewind the tape in this device.
    • mt -t /dev/rmt/0mnb offl will eject the tape in this device.


At command.
at command along with crontab command is used to schedule jobs.
at options time [ddate] [+increment] is syntax of at command.
for example if I have a script named usersloggedin which contains.
 #!/bin/ksh
who | wc -l
echo "are total number of people logged in at this time."
and I want to run this script at 8:00 AM. So I will first type at 8:00 %lt;enter>
usersloggedin %lt;enter>
I will get following output at 8:00 AM
      30
are total number of people logged in at this time.
Options:
  • -f file will execute commands in a file.
  • -m will send mail to user after job is completed.
  • -l will report all jobs that are scheduled and their jobnumbers.
  • -r jobnumber will remove specified jobs that were previously scheduled.


Chmod command.
chmod command is used to change permissions on a file.
for example if I have a text file with calender in it called cal.txt.
initially when this file will be created the permissions for this file depends upon umask set in your profile files. As you can see this file has 666 or -rw-rw-rw attributes.

ls -la cal.txt
-rw-rw-rw-    1 ssb      dxidev       135 Dec  3 16:14 cal.txt
In this line above I have -rw-rw-rw- meaning respectively that owner can read and write file, member of the owner's group can read and write this file and anyone else connected to this system can read and write this file., next ssb is owner of this file dxidev is the group of this file, there are 135 bytes in this file, this file was created on December 3 at time16:14 and at the end there is name of this file. Learn to read these permissions in binary, like this for example Decimal 644 which is 110 100 100 in binary meand rw-r--r-- or user can read,write this file, group can read only, everyone else can read only. Similarly, if permissions are 755 or 111 101 101 that means rwxr-xr-x or user can read, write and execute, group can read and execute, everyone else can read and execute. All directories have d in front of permissions. So if you don't want anyone to see your files or to do anything with it use chmod command and make permissions so that only you can read and write to that file, i.e.
chmod 600 filename.


Chgrp command.
chgrp command is used to change the group of a file or directory.
You must own the file or be a superuser.
chgrp [options] newgroup files is syntax of chgrp.
Newgroup is either a group Id or a group name located in /etc/group .
Options:
  • -h will change the group on symbolic links.
  • -R recursively descend through directory changing group of all files and subdirectories.


Chown command.
chown command to change ownership of a file or directory to one or more users.
Syntax is
chown options newowner files
Options
  • -h will change the owner on symbolic links.
  • -R will recursively descend through the directory, including subdirectories and symbolic links.


Crontab command.
crontab command is used to schedule jobs. You must have permission to run this command by unix Administrator. Jobs are scheduled in five numbers, as follows.
 Minutes                                          0-59
Hour                             0-23
Day of month           1-31
month                          1-12
Day of week             0-6 (0 is sunday)
so for example you want to schedule a job which runs from script named backup_jobs in /usr/local/bin directory on sunday (day 0) at 11.25 (22:25) on 15th of month. The entry in crontab file will be. * represents all values.
 25 22  15 * 0 /usr/local/bin/backup_jobs
The * here tells system to run this each month.
Syntax is
crontab file So a create a file with the scheduled jobs as above and then type
crontab filename .This will scheduled the jobs.


Date command.
Date displays todays date, to use it type 
date at prompt. 
Sun Dec  7 14:23:08 EST 1997
is similar to what you should see on screen.


Df command.
df command displays information about mounted filesystems. It reports the number of free disk blocks. Typically a Disk block is 512 bytes (or 1/2 Kilobyte).
syntax is
df options name 
Options
  • -b will print only the number of free blocks.
  • -e will print only the number of free files.
  • -f will report free blocks but not free inodes.
  • -F type will report on an umounted file system specified by type.
  • -k will print allocation in kilobytes.
  • -l will report only on local file systems.
  • -n will print only the file system name type, with no arguments it lists type of all filesystems


Du command.
du command displays disk usage.


Env command.
env command displays all the variables.


Finger command.
finger command.


PS command
ps command is probably the most useful command for systems administrators. It reports information on active processes.
ps options
options.
  • -a Lists all processes in system except processes not attached to terminals.
  • -e Lists all processes in system.
  • -f Lists a full listing.
  • -j print process group ID and session ID.


Ruptime command.
ruptime command tells the status of local networked machines.
ruptime options
options.
  • -a include user even if they've been idle for more than one hour.
  • -l sort by load average.
  • -r reverse the sort order.
  • -t sort by uptime.
  • -i sort by number of users.


Shutdown command.
Shutdown command can only be executed by root. To gracefully bring down a system, shutdown command is used. 
options.
  • -gn use a grace-period of n seconds (default is 60).
  • -ik tell the init command to place system in a state k.
    • s single-user state (default)
    • 0 shutdown for power-off.
    • 1 like s, but mount multi-user file systems.
    • 5 stop system, go to firmware mode.
    • 6 stop system then reboot.
  • -y suppress the default prompt for confirmation.


Stty command
stty command sets terminal input output options for the current terminal. without options stty reports terminal settings.
stty options modes < device
options
  • -a report all options.
  • -g report current settings.
Modes
  • 0 hang up phone.
  • n set terminal baud.
  • erase keyname, will change your keyname to be backspace key.


Who command
who command displays information about the current status of system.
who options file
Who as default prints login names of users currently logged in.
Options
  • -a use all options.
  • -b Report information about last reboot.
  • -d report expired processes.
  • -H print headings.
  • -p report previously spawned processes.
  • -u report terminal usage.