Sunteți pe pagina 1din 68

PL/SQL

PL/SQL is a procedural extension to non procedural language SQL. It is a block structural language. PL/SQL is developed by Oracle Corporation. Used only with oracle. It process only row at a time where non-procedural language process a set of rows at a time. It supports to execute a block of statements at once. Supports variables and constraints. PL/SQL can use for both server side and client side development. PL/SQL constraints are not database objects (Constraints not stored in database) Variable supports only NOT NULL and DEFAULT constraints. It supports error handling. Supports conditional constructs (if then...End if). It supports iteration controls(loops) It supports sub programs

BLOCK STRUCTURE: PL/SQL programs are divided up into structures known as blocks, with each block containing PL/SQL and SQL statements. A PL/SQL block has the following structure: [DECLARE Declaration _statements/variable _declaration] ` BEGIN Executable _statements;

[EXCEPTION Exception _handling _statements]; END; The PL/SQL program contain three statements 1. Declarative Section (Optional): In this section all variables are declared. 2. Executable Section: This section must have at least one executable statement.

3. Exception Section: It is used to handle the abnormal situations, and this section may is optional in the program but recommended.

Simple PL/SQL Block: BEGIN Null; END; Place the semicolon (;) end the SQL statement or PL/SQL control statement. Section keywords DECLARE, BEGIN, EXCEPTION should not contain a semicolon (;) END and other Pl/SQL statements should applied with the semicolon at end. Use forward slash (/) to run the Anonymous block in SQL*PLUS buffer. Place a period (.) to close a SQL*PLUS buffer without running the PL/SQL program. Semicolon within the PL/SQL block does not close or runs the SQL buffer In PL/SQL an error is called as an exception.

TYPES OF BLOCKS: 1. Anonymous blocks 2. Named blocks Labeled blocks Subprograms Triggers Anonymous blocks: The block which is not having any name is called as anonymous. It cannot be called in any other PL/SQL program or may be in any other applications. BEGIN Dbms_output.put_line (My first program); END;

Example:

NAMED BLOCKS; The block which is having name is called as named block. It can be called in another PL/SQL programs and as well as applications.

Example: Subprograms, Triggers Subprograms: Subprograms are procedures and functions. They can be stored in the database as stand-alone objects, as part of package or as methods of an object type. Triggers: Triggers consist of a PL/SQL block that is associated with an event that occur in the database. Nested blocks: A block can be nested within the executable or exception section of an outer block. VARIABLES IN PL/SQL: Variables are use to store data values. They represent the memory locations. We need a data type for a variable. Oracle supports bind variable and host variables/PL/SQL variables.

BIND VARIABLE: Variable which is defined at SQL prompt called as bind variable. To declare a bind variable in the SQL*Plus environment, you use the command VARIABLE.

For example: VARIABLE g _return _value NUMBER; HOST VARIABLES: Which are defined in a declarative section called as host or pl/sql variables. Upon declaration, the bind variables now become host to that environment, and you can now use these variables within your PL/SQL programs, such as packages, procedures, or functions.

PL/SQL variables supports all built in data types, user defined data types. User defined data types are: PL/SQL Record PL/SQL Table Ref cursor/dynamic cursor. Oracle contains two types of assignment operators. 1) := It is assignment operator for external value. Example: variable _name:=value; 2) INTO It is used for internal value. Example: Select ename INTO vename from EMP where empno=7788; VARIABLE DECLARATION: Syntax: DECLARE Variable _name <Data type>[:= value]; Example:Declare V _Name varchar2 (20):=smith; A number; X number default 6; Y constant number:=8; M constant number default 10; P constant number not null:=7; Doj date default sysdate; F Boolean:=true; When ones constant is used re-assignment is not possible, CONSTANT is a key word.

Executable statements: We can use DRL, DML, TCL in a PL/SQL program but we cannot use the DDL,DCL directly in a PL/SQL program. Select statement syntax: Select name,sal into v_name,e_sal from employees where empno=7788; Types of Comments: Oracle supports the two types of comments. 1. -- (Single line comment) 2. /* multi Line Comment */ The comments are ignored by compilers which are there in source code.

DBMS_OUTPUT.PUT_LINE (message||variable name) It is use to print the variable value and message DBMS_OUTPUT is a built in package. PUT_LINE is a procedure which is a part of package. It contains a single parameter. No case sensitive.

SET SERVER OUTPUT ON (Environment command,use to activate the DBMS statements) Example: Question: write a pl/sql program accepts two variables and display the sum.

Declare Vfno number:=&fno; Vsno number:=&sno; Vsum number;

Begin

Vsum:= vfno+vsno; Dbms_output.put_line(the sum of vfno and vsno is:||vsum); End; Or

Begin Dbms_out.put_line(the sum of fno and sno is:||(&fno+&sno)); End; 2 . write program to display employeename,sal,comm.,deptno and netsal from emp(accept empno number as input); Declare Vname varchar2(10); Vsal number(7,2); Vcomm number(7,2); Netsal number; Begin Select ename,sal,comm.,deptno into vname,vsal,vcomm,vdeptno from emp where deptno:=&empno; Netsal:=sal+nvl(vcomm,0); Dbms_output.put_line(the emp details are:||vname|| ||vsal|| ||vcomm|| ||vdeptno|| ||netsal); End; Vdeptno number(2);

NESTED BLOCKS: PL/SQL supports the nested blocks. Declare -------------Begin | | | | MIAN BLOCK | | | Executable statements; .; Declare Begin Executable statements; ; End; NESTED BLOCK;

---------------End; while nesting one block inside another block that define inside another block is called INNER BLOCK; Forward referencing is possible, but backward referencing is not possible. Example: Declare M number:=100; Begin M: =200; Declare N number: =300; Total number; Begin M: =500;

Total: =M+N; Dbms_output.put_line(the sum of M and N is:||Total); End; Dbms_output.put_line(the M value is:||M); End; OUTPUT: The sum of M and N is: 800 The M value is: 500 In this block if we want display M value as 100 or 200 or 300 is not possible, because backward reference is not possible we can avoid this by using LABELED BLOCK. LABELED BLOCK: A block represented with a label called as label block. How to convert anonymous block to LABEL BLOCK? We need to place the label before the declare keyword. The label also can appear after the END keyword and it is optional. The advantage of label blocks is we can access the outer block variable when the inner block is having same variable.

The labels appear in angle brackets. << >> Example: <<block1>>Declare M number:=100; Begin M:=200; <<block2>> declare M number; N number:=300; Total number; Begin M:=500; Block1.M:=600; (angle brackets)

Total:= N+block1.M; Dbms_output.put_line('the total is:'||Total); End block2; Dbms_output.put_line('the main block m value is:'||M); End block1; VARIABLE ATTRIBUTES: There are two types of attributes are there 1. Column Type 2. Row Type. 1. Column type: By using this variable attribute we can make the variable data type and size independently. Syntax: <variable name> <table name>.<column name>%type; Example: vname emp.ename%type; 2. Row type: It is used to declare a record. Syntax: <variable name> <table name>.%row type; Example: i emp%rowtype; Program: Write a pl/sql program to display the employeename, hiredate,sal,deptno,netsal for entered employeename; Declare i emp%rowtype; netsal number; begin i.empno:=&eno;

select ename,sal,comm, hiredate,deptno into i.ename,i.sal,i.comm,i.hiredate,i.deptno from emp where empno=i.empno; netsal:=i.sal+nvl(i.comm,0); dbms_output.put_line(the emp details are :||i.ename|| ||i.sal|| ||i.hiredate|| ||netsal|| ||i.deptno); end; OUTPUT: Enter value for eno: 7788 old 5: i.empno:=&eno; new 5: i.empno:=7788; the emp details are :SCOTT 5800 09-DEC-82 5800 20 PL/SQL procedure successfully completed. Note: Here i.ename,i.sal,i.hiredate treated as variable names. CONTROL STATEMENTS: PL/SQL can also process the data using flow of control statements. PL/SQL helps us to manipulates and process oracle data using control ststements. The flow of control statements can be classified into following categories. 1. Conditional control 2. Iterative control The sequence of statements can be executed based on a certain conditions. Based on IF statements IFTHEN.END IF IFTHENELSEEND IF IFTHEN...ELSIFEND IF

IF..THEN..END IF Syntax: IF condition THEN Sequence of statements; END IF; After if condition one executable statement must be there. When IF..THEN executed condition is evaluated true or false. Conditions are compared by using operators. One IF keyword can manage n no. of conditions ,at a point of time using logical connections like AND, OR If condition is false or null then the control posses the statement after END IF.

Example: Begin If ascii(A)=65 then Dbms_output.put_line(it is true); End if; End; Write a pl/sql program to hike the salary as 35% if entered employee salary is less than 2000.display the ename, hiked salary,deptno as a output.

Declare I emp%rowtype; Begin Select empno,ename,sal,deptno into i.empno,i.ename,i.sal,i.deptno from emp Where empno=&empno; if i.sal<2000 then i.sal:=i.sal+i.sal*0.35;

update emp set sal=i.sal where empno=i.empno; end if; dbms_output.put_line('the employee details are:'||i.ename||' '||i.empno||' '||i.sal||' '||i.dep end; OUTPUT: Enter value for empno: 7876 old 5: Where empno=&empno; new 5: Where empno=7876; the employee details are:ADAMS 7876 1755 20 PL/SQL procedure successfully completed. IF..THEN..ELSEEND IF This statement enables us to specify two different groups of statements for execution. Syntax : IF condition THEN Executable statements; ELSE Executable statements; END IF; Example: Write a pl/sql program to hike the comm. As 15% when employees having a comm..otherwise give the comm as 200 for entered employee number. Display employeename,sal,updated commission. Declare I emp%rowtype; Begin Select ename,sal,comm into i.ename,i.sal,i.comm from emp where empno=&empno;

IF i.comm is not null then i.comm:=i.comm+i.comm*0.15; else i.comm:=200; end if; update emp set comm=i.comm where empno=i.empno; dbms_output.put_line(the employee details are:||i.ename|| ||i.sal|| ||i.comm); end; OUTPUT: the employee details are:SMITH 1000 200

IF..THEN..ELSIFEND IF: It enables us to specify more than two different groups of statements for execution. Syntax: IF Condition THEN Sequence of statements; ELSIF Condition THEN Sequence of statements; ELSE Sequence of statements; END IF; Write a PL/SQL program to update the employee sal with following conditions If employee job is clerk hhike the sal as 25% If employee job is salesman hike the sal as 35% Other than these two conditions hike 15%.

Declare I emp%rowtype; Begin Select ename,job,sal,deptno into i.ename,i.job,i.sal,i.deptno from emp Where empno=&no; If i.job=CLERK then i.sal:=i.sal+i.sal*0.25; elsif i.job=SALESMAN then i.sal:=i.sal+i.sal*0.35; else i.sal:=i.sal+i.sal*0.15; end if; update emp set sal=i.sal where empno=i.empno; dbms_output.put_line(the updated salary is:||i.sal|| ||i.job); end; CASE EXPRESSION: It is similar to a switch statement in C language. Case is introduced in PL/SQL in Oracle 8i. When a particular condition is evaluated to TRUE, the group of statements associated to this condition is executed. We can evaluate conditions using the normal conditional operators for SQL*PLUS operators. Syntax: CASE test_var WHEN value1 THEN

Sequence of statements; WHEN value2 THEN Sequence of statements; WHEN valuen THEN Sequence of statementsn; [ELSE Statement;] END CASE; Where test_var is the variable or expression to be tested, value1 through valuen are the comparison values. If none of the values are equal then else sequence will be executed. Write a pl/sql program to display the month name for entered month number as input; DECLARE M_NUMBER NUMBER:=&NO; M_NAME VARCHAR2(10); BEGIN CASE M_NUMBER When 1 then M_name:=JANUARY; WHEN 2 THEN M_NAME:=FEBRUARY; WHEN 3 THEN M_NAME:=MARCH; WHEN 4 THEN M_NAME:=APRIL; WHEN 5 THEN M_NAME:=MAY; WHEN 6 THEN M_NAME:=JUNE; WHEN 7 THEN M_NAME:=JULY;

WHEN 8 THEN M_NAME:=AUGUST; WHEN 9 THEN M_NAME:=SEPTEMBER; WHEN 10 THEN M_NAME:=OCTOBER; WHEN 11 THEN M_NAME:=NOVEMBER; WHEN 12 THEN M_NAME:=DECEMBER; ELSE M_NAME:=UN KNOWN; END CASE; DBMS_OUTPUT.PUT_LINE(THE MONTH IS :||M_NAME); END;

Write a pl/sql program to display employee department name for entered employee name; DECLARE VDNAME VARCHAR2(10); VDEPTNO NUMBER; BEGIN SELECT DEPTNO INTO VDEPTNO FROM EMP WHERE EMPNO=&ENO; CASE VDEPTNO WHEN 10 THEN VDNAME:='ACCOUNTING'; WHEN 20 THEN VDNAME:='REASERCH'; WHEN 30 THEN VDNAME:='SALES';

WHEN 40 THEN VDNAME:='OPERATORS'; ELSE VDNAME:='UN KNOWN'; END CASE; DBMS_OUTPUT.PUT_LINE('THE EMPLOYEE DEPORTMENT NAME IS:'||VDNAME); END;

LOOPS Loops repeat a statements or sequence of statements multiple times. There are three loop types 1. Basic or Simple loop 2. For loop 3. While loop 1.Simple loop: Syntax : LOOP Sequence of statements; END LOOP; The sequence of statements will be executed between keywords LOOP and END LOOP Every loop start with LOOP keyword and end with END LOOP key word; The simple loop can be terminated by using. A. EXIT statement.

Syntax :

exit[when condition];

B. By using IF condition Syntax: If condition then Exit; End if; C. By using GOTO operator. EXIT Statement: Use to terminate simple loop statements. Once loop is terminated the control passes to the next statement after the END LOOP; The EXIT statement should always be placed inside the loop only. The loop terminates its process when the condition state is TRUE.

Program: Declare N number:=1; Begin Loop Dbms_output.put_line(n); End loop; End; Write a pl/sql program to display sequence of 1 to 10 numbers. Declare N number:=1; Begin Loop Exit when n>10

Dbms_output.put_line(n); N:=N+1;

End loop;

End;

Note : There are no increment operator like a++,a-- C language in backend. How to terminate a loop by using if condition. Example: Declare A number:=100; Begin Loop If a=250 then Exit; End if; a:=a+25; dbms_output.put_line(a); end loop; end; 2.WHILE LOOP: It is a pre tested loop. The while loop statement includes a condition associated with sequence of statements. If condition evaluates true then sequence of statements will be executed, again resumes at the beginning of the loop. If condition evaluates false or null, then the loop id by passed and the control passes to the next statements. Syntax : While condition LOOP Statement1; END LOOP;

Note : condition is evaluated at the beginning of each condition. Write a pl/sql program to display 1-10 horizontally.
DECLARE N NUMBER:=1; V VARCHAR2 (100); BEGIN WHILE (N<=10) LOOP V: =V||' '||N; N: =N+1; END LOOP; DBMS_OUTPUT.PUT_LINE (V); END;

FOR LOOP: It is a numeric for loop Synyax: FOR loop_counter IN [REVERSE] lower_bound..upper_bound LOOP Statements; END LOOP; Lower_bound ..higher_bound is range operator. The reverse is optional to display the higher_bound to lower_bound we can use the reverse. Loop counter is a implicit variable it is a numeric data type variable. We cannot perform any arithmetic operations on this implicit variable.

Write a program to display 1 to 10 numeric numbers, using for loop. Declare Begin For I in 1..10 Loop Dbms_output.put_line(i);

End loop; End; Note : In normal condition && accept static value. But in PL/SQL program & accept a static value in a loop. Write a pl/sql program to display factorial value for entered number. Declare Vnumber number:=&no; Vfact number:=1; Begin For v_counter IN reverse 1..vnumber Loop Vfact:=Vfact*v_counter; End loop; Dbms_output.put_line(the factorial of||vnumber||is:||vfact); End;

How to terminate a loop by using GOTO labels. Note : create table temp_table (count number,var varchar2(15)); Example: Declare V_counter number:=1; Begin Loop Insert into temp_table values(v_counter,loop counter); V_counter:=v_counter+1;

If v_counter>=50 then Goto endofloop; End if; End loop; <<endofloop>> Insert into temp_table(count) values(done); End; Note : after the label there must be one executable statement. CURSOR MANAGEMENT: In order to process a SQL statement Oracle will allocate an area of memory known as a context area (cursor area). PL/SQL uses this context area to store or execute the sql statements. The information retrieved from data base table, which is available in context area is known as active set. A cursor is used to process multiple rows using PL/SQL.

Types of cursors: 1. Implicit cursors 2. Explicit cursors

1.Implicit cursors: It is a cursor that automatically declared by Oracle every time a SQL statement is executed. These are created are erased automatically. These are identified by SQL %< cursor attribute> Cursor contains four attributes; these are used by SQL as a prefix. A cursor is automatically associated with every DML statement. During the process of an implicit cursor, Oracle automatically performs the operations like DECLARE,OPEN,FETCH and CLOSE of the context area.

Cursor attributes: Cursor attributes are available in pl/sql that can be applied to cursor name in a pl/sql block,similar to %type and %rowtype. The attributes are: %FOUND %NOT FOUND %ISOPEN %ROWCOUNT %FUOND: Boolean attribute that evaluates to TRUE if the most recent SQL statement effects one or more rows. %NOT FOUND: TRUE, if does not affect any rows %IS OPEN: Boolean attribute that evaluates to TRUE if the cursor is open else evaluates to FALSE %ROW COUNT: Number rows affected by the most recent sql statement(an integer value) Implicit cursor: Syntax: SQL%(attribute value); Write a pl/sql program to update the salary for entered job display the count of rows updated declare vjob emp.job%type:='&job'; begin update emp set sal=sal+1000 where job=vjob;

dbms_output.put_line(sql%rowcount||'rows were updated'); if sql%notfound then dbms_output.put_line('data not found ,no rows updated'); end if; end; write a pl/sql program to update the salary of employee with following criteria. If job is clerk hike sal 15%. If job is salesman hike 25%. Other than these two hike 35%. Insert updated detailes in bonus table. Program: declare begin for i in(select empno,ename,job,sal,comm. from emp) loop if i.job=clerk then i.sal:=i.sal+i.sal*0.15; elsif i.job=salesman then i.sal:=i.sal+i.sal*0.25; else i.sal:=i.sal+i.sal*0.35; end if; update emp set sal=i.sal where empno=i.empno;

insert into bonus values(i.ename,i.job,i.sal,i.comm); end loop; end; 2.Explicit cursor: Explicit cursors are explicitly declared by the programmer. This cursor is declared within the pl/sql block, and allows sequential process of each row of the returned data from data base.

The life cycle of explicit cursor gives through 4 stages. DECLARE OPEN FETCH CLOSE

1.Declare: The cursor statement is used to declare explicitly in declarative section. Cursor is a variable It is a virtual table.

Syntax : CURSOR <cursor name> is <select statement>; *select statement is mandatory. Note : In select statement include the most of usual clauses except INTO clause If we use INTO clause there is no use.

Example: Declare Vsal number; Cursor c1 is select sal into vsal from emp Where empno=7788;

[open c1] Dbms_output.put_line(the sal is:||vsal); End; *here vsal value is null, because using INTO clause no use. In cursor statement any assignment is not possible. 2.OPEN: Here query execution is done. Now we can fetch the data.

Syntax: OPEN <cursor name>; Example: OPEN C1; The cursor will now point to the first row in the active set. 3. FETCH: The retrieval of data into the pl/sql variable or host variable is done through FETCH statement.

Syntax: FETCH <cursor name> INTO variable;

Fetch should be the within the loop to terminate the loop we should use the cursor attributes.

4. CLOSE: Without closing the cursor not possible to reopen. It explicitly close the cursor. Allowing it to be reopened, if required The active set can be re-established several times Syntax: CLOSE <cursor name>; Example: CLOSE c1;

Active set: The set or rows returned by a multiple row query is called the active set. Explicit cursor attributes should prefixed with cursor name. <cursor name>%attribute; Example : C1%found; C1%not found; C1%rowcount; C1%isopen; Write a pl/sql program to give commission with following criteria. If employee not having commission give comm. As 300 If commission is 0 give commission as 250 Other than these two hike commission as 15%. Display ename,hiked comm.,deptno. Program: Declare Cursor c1 is select empno,ename,sal,deptno from emp; Vempno emp.empno%type; Vname emp.ename%type; Vcomm emp.comm%type; Vdeptno emp.deptno%type; Begin Open c1 Dbms_output.put_line(the employee details are:); Loop Fetch c1 into vempno,vname,vcomm,vdeptno; Exit when c1%notfound;

If vcomm is null then vcomm:=300; Elsif vcomm=0 then vcomm:=250; Else Vcomm:=vcomm+vcomm*0.15; End if; Update emp set comm.=vcomm where empno=vempno; Dbms_output.put_line(vempno|| ||vname|| ||vcomm); End loop; Close c1; End; Write a pl/sql program to hike sal with following criteria. If employee job is clerk hike sal as 15%,if employee job is salesman 25% other than this two conditions hike sal as 35% of 30 deptno. Declare Cursor h_sal is select empno,ename,sal,job,deptno from emp Where deptno=30; I emp%rowtype; Begin Dbms_output.put_line(the emp details are:) open h_sal; loop fetch h_sal into i.empno,i.ename,i.sal,i.job,i.deptno; exit when h_sal%not found; if i.job=CLERK then i.sal:=i.sal+i.sal*0.15;

elsif i.job=SALESMAN then i.sal:=i.sal+i.sal*0.25; else i.sal:=i.sal+i.sal*0.35; end if; update emp set sal=i.sal where empno=i.empno; dbms_output.put_line(rpad(i.empno,7)|| ||rpad(i.ename,7)|| ||rpad(i.sal,7)|| ||i.deptno); end loop; end; Note: if we close cursor before display output it will give error. Once cursor is closed if we use h_sal%rowcount it gives error. Explicit cursor with FOR loop: It is two types. a. Simple loop b. For loop Syntax : for <variable name> IN <cursor name> LOOP Statements; END LOOP; Advantages: No need to I. II. III. IV. Define explicit variable for cursor; Open a cursor explicitly Fetch a record explicitly No need to use the cursor attribute to close the cursor explicitly. close h_sal;

Write a pl/sql cursor to hike emp sal as 25% those are having sal<2000 of deptno 20. Declare Cursor cu is select empno,ename,sal,deptno from emp where deptno=20; Begin For I in cu Loop If i.sal<2000 then i.sal:=i.sal+i.sal*.25; update emp set sal=i.sal where empno=i.empno; dbms_output.put_line(i.ename|| ||i.sal|| ||i.deptno); end if; end loop; end; write a pl/sql program to display the deptno,lsal,hsal,total sal and no.of employees by using cursor. Declare Cursor cg is select deptno,min(sal) losal,max(sal) hisal,sum(sal) total_sal,count(empno) no_emp from emp group by deptno; Begin Dbms_output.put_line(the employee details are:); For I in cg Loop Dbms_output.put_line(i.deptno|| ||i.losal|| ||i.hisal|| ||i.total_sal|| ||i.no_emp); End loop; End;

ADVANCED CURSOR: Parameter cursor: The cursor defined with a parameter called parameter cursor. Cursor parameters can be assigned with default values. The mode of cursor parameters can be only IN mode. By default in mode. Parameter is variable which is use to Pass the value to a program Receive the value from the program.

Note: No size for the parameter variable. Syntax: cursor <cursor name>(parameter name,datatype); Is Select statements; Write a pl/sql program to hike the employee sal as 15% if employee deptno is 10,20% if deptno is 20,other than these two hike as 35% on their salaries accept the job as input. Declare Cursor p_cur(pjob varchar2) is Select empno,ename,job,sal,deptno from emp where job=pjob; I p_cur%rowtype; Begin Open p_cur('&job'); Loop Fetch p_cur into I; Exit when p_cur%notfound;

If i.deptno=10 then i.sal:=i.sal+i.sal*0.15; elsif i.deptno=20 then i.sal:=i.sal+i.sal*0.20; else i.sal:=i.sal+i.sal*0.35; end if; update emp set sal=i.sal where empno=i.empno; dbms_output.put_line(rpad(i.ename,8)||' '||rpad(i.sal,8)||i.job||' '||i.deptno); end loop; close p_cur; end; Write a pl/sql program accept deptno from dept table and display ename,job,deptno Declare Cursor dc is select deptno from dept; Cursor ec(pdno in dept.deptno%type) Is Select ename,job,deptno from emp where deptno=pdno; Vdno dept.deptno%type; I ec%rowtype; Begin Open dc; Loop

Fetch dc into vdno; Exit when dc%notfound; Open ec(vdno); Loop Fetch ec into I ; Exit when ec%notfound; Dbms_output.put_line (rpad(i.ename,8)||rpad(i.job,8)||i.deptno); End loop; Dbms_output.put_line('________________'); Close ec; End loop; End; Cursor with group by clause: Writa a pl/sql cursor to display deptno,hisal,lowsal,no.of employees and total salary of each deptno. Declare Cursor cg is select deptno ,min(sal) lowsal,max(sal) hisal,sum(sal) totalsal,count(empno) noe from emp group by deptno; Begin For i in cg Loop Dbms_output.put_line(i.deptno||' '||'highsal'||' '||i.hisal||' '||'totalsal'||' '||i.totalsal||' '||'no.of emplyees'||' '||i.noe); End loop; End; '||'lowsal'||' '||i.lowsal||'

Subquery with explicit cursor: write a pl/sql program cursor to display deptno,dname,loc and no.of employees. Declare Cursor cq is select d.deptno,d.dname,d.loc,v.noe from dept d,(select deptno,count(*) noe from emp)v group by deptno where d.deptno=v.deptno; I cq%rowtype; --here cq%rowtype is cursor type attribute. Begin Open cq; Loop Fetch cq into I; Exit when cq%notfound; Dbms_output.put_line(rpad(i.deptno,8)|| ||rpad(i.dname,8)|| ||rpad(i.loc,8)|| ||i.noe); End loop; Close cq; End; EXCEPTION HANDLING: An exception in pl/sql block is raised during exception of block. It terminates the main body of action means a block always terminates when pl/sql raises an exception. We can specify an exception handler to perform final action. Trapping exception: The exception handling section consist of handler for all the exception. Each exception handler consists of a WHEN clause, which specifies an EXCEPTION that has to be handled.

Syntax: Exception When <exception1>[or exception2] then Sql statement1; Sql statement2; When <exception3> [or exception4] then Sql statement1; Sql statement2; When others then Sql statement1; Sql statement2; End; The others exception is optional exception handling clause that traps unspecified exceptions. The others should always be the last handler in the block. Types of exception: 1.Predefined Exception: Oracle has several predefined exceptions that correspond to the most common oracle errors. Each predefined exception begins with ORA followed by a number. As soon as the exception occurs oracle implicitly raise the exception and jumps into the EXCEPTION handle block, if proper exception handle is found manages the specific steps.

Predefined exception list: Error No ORA-0001 ORA-1001 ORA-1403 exception name DUP-VAL-ON-INDEX INVALID-CURSOR NO-DATA-FOUND description unique constraint violated illegal cursor operation no data found

ORA-1422 ORA-1722 ORA-1476

TOO-MANY-ROWS INVALID-NUMBER ZERO-DIVIDE

select into statement matches more one row conversion fails when divide by the any value by zero.

Write a pl/sql program to display netsal,gross,sal,empname for entered empno. Declare I emp%rowtype; Netsal number; Gross number; Begin Select ename,sal,comm. Into i.ename,i.sal,i.comm from emp where empno=&no; Netsal:=i.sal+nvl(comm,0); Gross:=i.sal+i.sal*0.35+i.sal*0.45-i.sal*0.15; Dbms_output.put_line(the employee details are:||i.ename|| ||netsal|| ||gross); Exception When no_data_found then Dbms_output.put_line(employee no is not exist); When others then Dbms_output.put_line(some other errors); End; Note: Every block must have only one exception. Raise_application_error (error message): It is a built in function Enables you to specify user defined error message and also suspend the task. It contains two parameters The error number, the limit -20,000 to -20,999 Error message it is use to display the message.

Raise_application_error display the message and suspend the task, whereas put _line Simply display the message. It is a standard alone procedure (not a part of package). Whereas put_line is a part of package. Raise_application_error has two parameters whereas put_line has only one parameter.

Write a pl/sql program to hike the emp sal as 35%,if emp sal is above 2000, if emp sal less than 2000 display the appropriate msg and stop the process. Declare I emp%rowtype; Begin i.empno:=&no; select ename,sal,deptno into i.ename,i.sal,i.deptno from emp where empno=i.empno; if i.sal<2000 then raise_application_error(-20456,'the employee sal is less than 2000,so no updation'); else i.sal:=i.sal+i.sal*0.35; update emp set sal=i.sal where empno=i.empno; end if; dbms_output.put_line('the employee details are:'||i.ename||' '||i.sal||' '||i.deptno); exception when no_data_found then dbms_output.put_line('the entered employee number'||' '||i.empno||' '||'not exist'); end; How to define user defined exceptions: Steps : 1. Declare exception 2. Raise in executable section exception using RAISE statement. 3. Handle the raised exception

Write a pl/sql program to hike sal as 15%,if emp having a sal,if employee is not having a sal raise the exception and provide the sal as 3000,display ename,sal,deptno. Declare I emp%rowtype; Sal_missing exception; --here exception is data type Begin Select empno,ename,sal,deptno into i.empno,i.ename,i.sal,i.deptno from emp where empno=&no; If i.sal is null then Raise sal_missing; Else i.sal:=i.sal+i.sal*0.15; update emp set sal=i.sal where empno=i.empno; dbms_output.put_line('the employee details are:'||i.ename||' '||i.sal||' '||i.deptno); end if; exception when no_data_found then dbms_output.put_line('the employee number is not exist'); when sal_missing then dbms_output.put_line('the employee not having salary ,so 3000 salary is added to employee'); update emp set sal=3000 where empno=i.empno; dbms_output.put_line(sqlcode||' '||sqlerrm); when others then dbms_output.put_line('unknown exception'); end;

Sqlcode: holds the currently raised number Sqlerrm: holds the currently raised exception. Non predefined errors: Steps: Declare exception Associate exception with oracle error number using pragma exception_init. Handle the raised exception.

pragma is a directive of compiler which tells compiler to associate error number with user declared exception at compile timer. syntax: pragma exception_init(<exception name>,<exception number>); It is use to handle the internal errors just like exception. To associate exception with error code (i.e program exception_init is deleted) Ecample: cretate table student(sid number constraint pk_sid primary key,name varchar2(10)); insert into student values(100,rahul); program: declare sid_pk exception; pragma exception_init(sid_pk,-0001); begin insert into student values(&sid,'&name'); exception when sid_pk then dbms_output.put_line('the sid alredy exist,please enter unique sid'); end;

COLLECTIONS IN PL/SQL

How to assign more than one value to variable? Oracle supports the five types of collections. 1. 2. 3. 4. 5. Objectives Varray Pl/sql record Pl/sql table Ref cursor(or)Dynamic Objectives and varray are the database objects, which are stored into the data base. These two data types are used in SQL as well as PL/SQL. pl/sql record,pl/sql table and ref cursor are user defined datatypes which are not stored in anywhere in database. These data types can be used only in pl/sql.

Composite data type: There are two types of composite data types. 1. PL/SQL Record. 2. PL/SQL Table. 1. PL/SQL Record: Holds the list of elements of different data types. Similar to structures in C. Syntax: Type <record name> IS record (Element1 <data type>, element2 <data type>, element3 <data type>);

write a pl/sql program to display empno,ename,sal,deptno,dname and gross sal Declare type emp_rec is record(eno number,name emp.ename%type,basic emp.sal%type,I dept%rowtype,gross number); e emp_rec; begin e.eno:=&eno; select ename,sal,dept.deptno,dname into e.name,e.basic,e.i.deptno,e.i.dname from emp,dept where emp.deptno=dept.deptno; e.gross:=e.basic+e.basic*0.35+e.basic*0.45-e.basic*0.15; dbms_output.put_line(e.name||' '||e.basic||' '||e.i.deptno||' '||e.i.dname||e.gross); end; 2. PL/SQL Table: It holds the elements of similar data types. Syntax: Type <table name> is table of <data type> index by binary_integer. An index by table is syntactically similar to C array. Program: Declare Type name is table of varchar2(20) index by binary_integer; n name; begin n(-1):='golden'; n(0):='gate'; n(1):='hyd';

dbms_output.put_line(n(-1)||' '||n(0)||' '||n(1)); end; Nested PL/SQL record: The PL/SQL record data type can used for another PL/SQL record element data type; Example: Declare type pf_info is record(pfno number(4),amount number(14,2)); type emp_rec is record(eid number(4),name varchar2(20),basic number(12,2),pf pf_info); --pf_info another pl/sql record. Type empt is table of emp_rec index by binary_integer; ctr number(3):=1; e empt; Begin for I in(select empno,ename,sal basic,sal*0.15 pamt from emp where sal>2000) loop e(ctr).eid:=i.empno; e(ctr).name:=i.ename; e(ctr).basic:=i.basic; e(ctr).pf.pfno:=i.empno+5; e(ctr).pf.amount:=i.pamt; ctr:=ctr+1; end loop; dbms_output.put_line('employee details are:'); for k in 1..e.count

loop dbms_output.put_line(e(k).eid||' '||e(k).name||' '||e(k).basic||' '||e(k).pf.pfno||' '||e(k).pf.amount); end loop; end; Returning into clause(8.0): Define two bind variables a,b >var a number; > var b varchar2(20); update emp set sal=sal+sal*0.15 where empno=7788 returning sal,ename into :a,:b --the updated sal and ename is assigned into a,b bind variables to see the value stored in bind variable is >print :a :b; BULK COLLECT: Use to collect more than one row at a time. it is used with select ,update, delete and fetch. by using bulk collect we can avoid cursors

Example: select ename,sal bulk collect into p,q from emp; [Here p,q must be pl/sql variables] Program: Declare type name is table of emp.ename%type index by binary_integer; type pays is table of emp.sal%type index by binary_integer; n name;

p pays; begin select ename,sal bulk collect into n,p from emp; for I in 1..n.count loop dbms_output.put_line(rpad(n(i),8)||' '||rpad(p(i),8)); end loop; end; write a pl/sql program to delete the 30 dept employees if any employee getting a sal between 1000 to 2000 insert empno,ename and empsal into trace table. [create table trace as select empno,ename,sal from emp where 1=2;] declare type eno is table of emp.empno%type index by binary_integer; type ename is table of emp.ename%type index by binary_integer; type pays is table of emp.sal%type index by binary_integer; e eno; n ename; p pays; begin delete from emp where deptno=30 returning empno,ename,sal bulk collect into e,n,p; --Here deleted records are stored in e,n,p for I in 1..e.count loop if p(i) between 1000 and 2000 then insert into trace values(e(i),n(i),p(i));

end if; end loop; end; Cursor with composite data type: write a plsql program to hike the employee sal with following requirement if emp having comm hike sal as 15%,if comm. is zero hike sal as 100,if emp comm is null hike sal as 200 by using cursor. Declare cursor cs is select empno,sal,comm from emp; type pays is table of emp.sal%type index by binary_integer; type eno is table of emp.empno%type index by binary_integer; type comm is table of emp.comm%type index by binary_integer; e eno; p pays; c comm; begin open cs; fetch cs bulk collect into e,p,c; for I in 1..e.count loop If c(i) is not null and c(i)<>0 then p(i):=p(i)+p(i)*0.15; elsif C(i) =0 then

P(i):=p(i)+100; else p(i):=p(i)+200; end if; update emp set sal=p(i) where empno=e(i); dbms_output.put_line(rpad(e(i),8)||' '||rpad(p(i),8)||rpad(c(i),8)); end loop; end; SUB PROGRAMS IN PL/SQL Procedures Functions Sub programs are use to provide the modularity and encapulate a sequence of statements. Once sub programs are built and validate, they can be used in no.of applications. Sub program also provide abstraction. Sub programs are named PL/SQL blocks that can accepts parameters. A sub program can also have a declarative part,an executable part and an exception handling part.

Features of sub program: Modularity Reusability Maintainability PROCEDURES: Types of Procedures A. Stand-alone schema object. B. A part of the package.

A. Stand-alone schema object: A procedure which is created as a data base object called as a Stored Procedure or Stand-alone schema object. B.Part of the package: A procedure which is created inside of the package called as a part of the package. It is not stored anywhere in the data base separately as a data base object. Parts of procedure 1. Specification Declarative of procedure name, Parameters. 2. Body PL/SQL block, Code. Syntax: CREATE [or replace] PROCEDURE <PROCEDURE NAME> [(parameter [mode] <data type>)] IS/AS [Local variable;] BEGIN <EXECUTABLE STATEMENTS>; [Exception When condition then Executable statement;] END; Or replace is used to modify the procedure source code. Procedure name: It is used to identify the procedure. It should be short and meaningful. Parameters: It is optional the parameter contains three types of mode IN, OUT, INOUT. Parameter Data type is mandatory and size should not be mentioned. Parameters support the integrity constraints (only NOT NULL, DEFAULT).

Local variables defined after is/as keyword these can use only in this procedure. The Procedure body will start after is/as keywords. Executable section must have at least one executable statement. Exception is optional, but recommended.

Invoke the stored Procedure: At sql prompt: sql> Execute <procedure name>(required arguments); In PL/SQL block: Begin <procedure name>[(required arguments)]; End; Write a pl/sql procedure to calculate the simple and compound interest. create or replace procedure int_cal(p in number,n in number,r in number) is si number; ci number; begin si:=(p*n*r)/100; ci:=p*power((1+r/100),n); dbms_output.put_line('the simple interest and compound interest formula are:'||si||' '||ci); end int_cal; To execute procedure execute int_cal(10000,12,2); How to call in different pl/sql program: begin

int_cal(10000,12,2); end; write a pl/sql procedure to update employe salary with bonus if emp job is clerk the bonus should be 15% on their netsal,if emp job is salesman the bonus is 25% on their netsal.display o/p as ename,job,sal,bonus. create or replace procedure sal_bonus is cursor sb is select empno,ename,job,sal+nvl(comm,0) netsal from emp; I sb%rowtype; Bonus number; Begin Open sb; Loop Fetch sb into I; exit when sb%notfound; if i.job='CLERK' then bonus:=i.netsal*0.15; elsif i.job='SALESMAN' then bonus:=i.netsal*0.25; else bonus:=i.netsal*0.35; end if; update emp set sal=sal+bonus where empno=i.empno; dbms_output.put_line(i.ename||' '||i.job||' '||bonus); end loop; close sb;

end sal_bonus; The procedure can be used in At SQL(but we cannot use like function) PL/SQL block Procedure Function Trigger Package

PROCEDURE with Parameter mode. There are three parameter modes i.e. IN, OUT, INOUT. IN: OUT: Used to return a value from subprogram It cannot carry a value into a subprogram. Initialized in subprogram It is default. always accepts a value into a subprogram It cannot be assigned with a value in subprogram.

INOUT: Carries a value into a subprogram Returns a value from subprogram Max 32 arguments supported by subprogram

Syntax: <parameter name>[parameter mode]<datatype> program: create or replace procedure p_square(n in number,s out number,c out number); is begin s:=n*n;

c:=n*n*n; end p_square; Example for IN OUT: create or replace procedure sqr(n in out number) is begin n:=n*n; end sqr; Sending arguments can be performed by using 1. Named notation: Through the names of parameter we can pass the arguments. we use the named notation operator (=>) to perform this task. Example: Exec add_dept(ploc=>HYD,pdname=>ACC) 2. Position notation : Example :Exec add_dept(hyd,acc); DROPPING PROCEDURE: syntax: Drop procedure <procedure name> Example: Drop procedure p1; Nested procedure: Create or replace procedure add_emp as begin insert into emp(empno,ename,sal,deptno) values(1001,EFCODD,2000,50) commit;

end add_emp; create or replace procedure add_dept as begin insert into dept values(50,EXPORT,HYD); add_dept; end add_dept;

Note: Here add_emp procedure contains commit,this effected in add_dept when we call add_emp in add_dept. Pragma autonomous_transaction(8i): It allows too write TCL in triggers Used also in nested procedure to make each procedure in depended for TCL If we use the pragma autonomous_transaction in called procedure the commit is committed only for called procedure transaction

Create or replace procedure add_emp pragma autonomous_transaction as begin insert into emp(empno,ename,sal,deptno) values(1001,EFCODD,2000,50) commit; end add_emp; create or replace procedure add_dept as

begin insert into dept values(50,EXPORT,HYD); add_dept; end add_dept; procedure with synonym: create synonym <synonym name> for <procedure name>; Note: We cannot synonym for procedure which is in package Example: Create public synonym sc_cal from cal_intr; Public synonyms are stored in DB _OBJECTS, we cannot drop Public Synonyms Procedure over Loading: Oracle supports the procedure, function overloading, it is possible only in package. A Procedure defines with same name with different signature called as Procedure overloading. Example: Different signatures: Different number of parameters proc1 (a number) proc1(a number number) Different types of parameters Proc1 (a number b varchar2) Different sequence of data types proc1 (a varcgar2, b number)

FUNCTIONS: A function is very similar to a procedure Function is a named pl/sql block Function may or may not take the parameters, but at most return a value Function must have a return clause in the executable section of a function Functions are mainly used to perform the calculation The data type of return value must be declared in the header of the function Procedures and Functions are different forms of the pl/sql blocks, with a declared executable, and exception section Procedures and Functions can be stored in the database od declared within a block A procedure call is a pl/sql statement by itself, while a function call is called as part of an exception A Function has output that needs to be assigned to a variable or it can be used in a select statement begin varname:=fun(); end; Note: Function is expression, where procedure is executable statement Procedure stores images, function cannot Bind Variable not support Boolean data type sql>var flag Boolean (It gives error) A Function can have more than one return statement, each exception should have a return statement Exception when condition1 then return; when condition2 then Function cannot call when it has RETURN data type a Boolean at SQL prompt

return; . when others then return; SYNTAX: create [or replace] function <function name>(parameter list) return datatype is [local variable] Begin <body> return(value) [here data type of value must be same as return data type] exception <defined pragmas> End [function name]; A Function can be in invoke at 1) Sql prompt sql>exec varname:=fun_name([arg1,arg2..]) 2) in pl/sql program begin varname:=fun_name([arg1,arg2.]) end; 3) In a select statement select fun_name([arg1,arg2.]) from dual or table_name;

Write a pl/sql user define function to calculate the compound interest. create or replace Function ci(p in number,n in number,r in number); return number is vci number; Begin vci:=p*power((1+r/100),n); return(vci); end ci;

How to call function: >var cir number >exec :cir:=ci(1000,12,2) >print :cir

>select ci(1000,12,2) compoundintr from dual;

>select ename,sal,ci(sal,12,2) cir from emp;

create or replace function ah_amt(amt number) return varchar2 is begin if amt>1000 then return ('high'); else return ('low'); end if; end;

select ah_amt(1200) from dual;

create synonym for function create public synonym fact_var for fact; >grant execute on fact to to public; DATABASE TRIGGERS: A set of pl/sql statements automatically executed whenever an DML statement is performed on a table. It is a pl/sql block like procedure Associated with table or view Trigger can be created either on table or view It is not called explicitly It is executed implicitly against an event take place for the table It is also database object,it is stored in USER_TRIGGER

EVENTS: INSERT/UPDATE/DELETE It does not accept parameters Used to implement user defined restriction on a table Used to impose business rules on data Provide high security Activated when tables are manipulated from other application

Trigger parts: There are two trigger parts It is use to indicate when to activate trigger 1. Before 2. After Trigger type: Row trigger: Trigger will be fired for every row manipulated

Statement Trigger: Trigger will be fired only once for DML statements Syntax: Create [or replace] trigger <trigger name> Before/after insert or update or delete

[Of <column name>]; ON <table name> [For each row] WHEN (<condition>); [Declare Begin <Execute statement>; [Exception condition] End [trigger name]; NOTE: Trigger name cannot be duplicate Trigger can be attached to table When condition is true, trigger will be executed otherwise not executed. Variable declaration;]

Qualifiers: The qualifiers can use in row level trigger, that are reference to the values available in DML statements. Syntax: : new.<column name> : old.<column name> insert into dept values(10,accounting,new york); deptno Dname Loc

10 20 30

Accounting Research Sales

New York Dallas Bostan

Update dept set dname=Sales where deptno=10; :old.dname=accountiog :new.dname=sales components of triggers: 1. Triggering event(insert,update,delete) 2. Trigger action(pl/sql code) 3. Trigger restriction(when) We have maximum 12 triggers Row level: After insert: before insert After update: before update After delete: before delete Table level: After insert before insert After update before update After delete before delete write a pl/sql program to avoid the duplicate dname&null value Create or replace trigger t_dn Before insert or update Of dname On dept For each row Declare

cnt number; Begin select count(dname) into cnt from dept where dname=:new.dname; if :new.dname is null then raise_application_error(-20567,dname cannot be null); elsif cnt>0 then raise_application_error(-20568,dname already exist,dname cannot be duplicate); end if; end t_dn; insert into dept values(50,null,hyd) It gives mutating error [When trigger contain s insert or update & delete then the mutating problem will be raised, this problem can be avoided by using pragma_autonomous_transaction] write a pl/sql trigger to trace the emp details into tab_del after delete. --create table tab_del-[create table tab_del(eid number,name varchar2(20),job varchar2(20),deptno number, dod date);]

Create or replace trigger trg_del after delete on emp for each row begin insert into tab_del values(:old.empno,:old.ename,z;old.job,:old.deptno,:sysdate); end trg_del;

=>delete from emp where deptno=10; [automatically 10 deptno details inserted into tab_del table] write a pl/sql trigger to trace the user and date of delete on emp table [create table trace(user_id varchar2(20),dod timestamp);] create or replace trigger del_trace after delete on emp for each row begin insert into trace values(user,sysdate); end del_trace; [if we delete 3 records,user details are inserted 3 times into trace table] *if we use statement level trigger the user details will be inserted only single time]. write a pl/sql program to insert employee information in bonus table as soon as insert into the table commit the transactions. create or replace trigger trg_insert before insert on emp for each row begin insert into bonus(:new,ename,:new.job,:new.sal,:new.comm); commit; end trg_insert; *So it will not give compilation error, it gives runtime error because of commit. insert into emp(empno,ename,job,sal,comm) values(1001,john,clerk,2000,300);

It gives runtime error as cannot commit in a trigger [Note: we cannot use TCL commands in trigger] To avoid this error we use pragma_autonomous_transaction. create or replace trigger trg_insert before insert on emp for each row declare pragma_autonomous_transaction; begin insert into bonus(:new,ename,:new.job,:new.sal,:new.comm); commit; end trg_insert; *when we say rollback only emp table records are rollbacked,but bonus transactions will be commited. Three events in a single Trigger: create or replace trigger trg_name before /after insert or update or delete on table name for each row when <condition> declare begin if inserting then sql statements;

end if; if updating then sql statements; end if; if deleting then sql statements; end if; Write a pl/sql trigger to insert the employee details according to the DML operations. [create 3 tables int_tab,del_tab,upd_tab] create or replace trigger trg_iud after insert or update or delete on emp for each row begin if inserting then insert into int_tab values(:new.empno,:new.ename,:new.sal); end if; if updating then insert into upd_tab values(:new.empno,:new.sal,:new.deptno); end if; if deleting then insert into del_tab values(:old.empno,:old.ename,:old.job); end if; end trd_iud;

Dropping a trigger: => Drop trigger <trigger name>; Example: drop trigger trg_del; Disabling all triggers on a table: Alter table emp disable all triggers; Alter table emp enable all triggers; Disabling single trigger: Alter trigger <trigger name> Disable; alter trigger <trigger name> Enable; INSTEAD OF TRIGGER (8i): Triggers on view Used to manipulate join views instead of insert --update --delete Example: [Create or replace view v1 As select *from emp;]

Create or replace trigger trg_view instead of delete on v1 begin dbms_output.put_line(record is removed); end trg_view; Note: Here no need of row level ,statement level

PACKAGE: It is a database object. It groups logically related plsql types,objects and subprograms. It has usually two parts 1. Specification 2. Body Package cannot be invoked, parameterized and nested. We cannot execute package directly. >exec package. Procedure is possible to execute. >exec pack1.proc1(p1,p2). NOTE: It allows the oracle server to read multiple objects into memory at once, means when we call packaged pl/sql construct for the first time, the whole package is loaded into memory. Components of package: Specification Body Note: Through the specification only body will be communicate Both are storing into database separately. Spec, body both have same name. Syntax of specification: Create or replace Package <package name> [public variable declaration]; [sub program declaration]; End [package name]; Is/as

Syntax of body: Create package body<package name> Is/as <private variable declaration>; <sub program bodies>; End [package name]; Invoking package constructs Execute <package name>.<program name>; Bodiless package: We can declare a package specification that does not need package body. Write a plsql package to display the two numbers total and multiplication. Create or replace package pac_am As Procedure add_num(a in number,b in number); Function mul_num(m in number,n in number); Return number; Result number; End pac_am; [Procedure and function will not store in database which are in package] Create or replace package body Pack_am As Proceduere add_num(a in number,b in number) Is Begin

Result:=a+b;

DIFFERENCE BETWEEN PROCEDURE AND FUNCTION

1. Function is mainly used in the case where it must return a value. Where as a procedure may or may not return a value or may return more than one value using the OUT parameter. 2. Function can be called from SQL statements where as procedure can not be called from the sql statements

3. Functions are normally used for computations where as procedures are normally used for executing business logic.

4. You can have DML (insert,update, delete) statements in a function. But, you cannot call such a function in a SQL query.

5. Function returns 1 value only. Procedure can return multiple values (max 1024).

6.Stored Procedure: supports deferred name resolution. Example while writing a stored procedure that uses table named tabl1 and tabl2 etc..but actually not exists in database is allowed only in during creation but runtime throws error Function wont support deferred name resolution.

7.Stored procedure returns always integer value by default zero. where as function return type could be scalar or table or table values

8. Stored procedure is precompiled execution plan where as functions are not. 9.A procedure may modify an object where a function can only return a value The RETURN statement immediately completes the execution of a subprogram and returns control to the caller

S-ar putea să vă placă și