Wednesday, September 20, 2006

Replacing Cursor with For Loops


Advantages of replacing curosors with for loop
-Implicitly declares its loop index as a %rowtype record
-opens, fetch and close operation are done automatically.
-It reduce coding and it is easy to understand.


----------------------------------
--Simple Select Procedure Example
----------------------------------
--Create Procedure
CREATE PROCEDURE SP_Print_Hello
AS
BEGIN
FOR IDX IN (Select ename from emp)
LOOP
DBMS_OUTPUT.PUT_LINE('Hello ' IDX.ename);
END LOOP;
END;


--Execute Procedure
begin
scott.sp_inc_salary ( );
end;


--Output
Hello SMITH
Hello ALLEN
Hello WARD
Hello JONES
Hello MARTIN
Hello BLAKE
Hello CLARK
Hello SCOTT
Hello KING
Hello TURNER
Hello ADAMS
Hello JAMES
Hello FORD
Hello MILLER
----------------------------------



-------------------------------------
--Manipulate Batch Update Statement
-------------------------------------
--Create Procedure
CREATE PROCEDURE SP_Increment_Salary
AS
mIncAmt number(5);
BEGIN
mIncAmt := 2000;
FOR IDX IN (Select empno,sal from emp)
LOOP
Update emp
Set sal = IDX.sal + mIncAmt
where empno = IDX.empno;
END LOOP;
END;


--Execute Procedure
begin
scott.SP_Increment_Salary ( );
end;


--OUTPUT
Procedure updated successfully....
-----------------------------------------

No comments:

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape