Introduction to the basic syntax for Oracle stored procedures _oracle

Source: Internet
Author: User
Tags commit error handling rollback rowcount throw exception oracle database

Oracle stored procedure basic syntax stored procedures
1 CREATE OR REPLACE PROCEDURE Stored procedure name
2 is
3 BEGIN
4 NULL;
5 end;

Line 1:
The Create OR REPLACE PROCEDURE is an SQL statement that notifies the Oracle database to create a stored procedure called skeleton, overwriting it if it exists;
Line 2:
The IS keyword indicates that the following will follow a pl/sql body.
Line 3:
The BEGIN keyword indicates the beginning of the Pl/sql body.
Line 4:
A NULL pl/sql statement indicates that nothing is done, and this cannot be deleted, because at least one sentence is needed in the pl/sql body;
Line 5:
End keyword Indicates the ending of the pl/sql body
Stored Procedure creation Syntax:
Create or Replace procedure stored procedure name (param1 in type,param2 out type)
As
Variable 1 type (value range); --VS_MSG VARCHAR2 (4000);
Variable 2 type (value range);

Copy Code code as follows:

Begin
Select COUNT (*) into variable 1 from table A where column name =param1;

If (judging condition) then
Select column name into Variable 2 from table a where column name =param1;
Dbms_output. Put_Line (' Print info ');
elsif (judging condition) then
Dbms_output. Put_Line (' Print info ');
Else
Raise anomaly name (No_data_found);
End If;
Exception
When others then
Rollback;
End;

Precautions:
1, the stored procedure parameter does not take the value range, in represents the incoming, out represents the output
Types can use legitimate types in any Oracle.
2, the variable takes a value range, followed by a semicolon
3, it is best to use the count (*) function to determine whether an action record exists before judging the statement
4, with Select ... Into ... Assigning values to variables
5, throw exception in code with raise+ exception name
Copy Code code as follows:

CREATE OR REPLACE Procedure Stored procedure name
(
--Defining parameters
Is_ym in CHAR (6),
The_count out number,
)
As
--Defining variables
VS_MSG VARCHAR2 (4000); --Error message variable
Vs_ym_beg CHAR (6); --Starting month
Vs_ym_end CHAR (6); --End of month
Vs_ym_sn_beg CHAR (6); --The beginning of the same month
Vs_ym_sn_end CHAR (6); --Termination month of the same period
--Define the cursor (simply a result set that can be traversed)

CURSOR cur_1 is
SELECT ...
From ...
WHERE ...
GROUP by ...;
BEGIN

--Using input parameters to assign the initial value to the variable, using the Oralce substr to_char add_months

To_date, such as the most common functions.
Vs_ym_beg: = SUBSTR (is_ym,1,6);
Vs_ym_end: = SUBSTR (is_ym,7,6);
Vs_ym_sn_beg: = To_char (Add_months (To_date (Vs_ym_beg, ' yyyymm '), -12), ' yyyymm ');
Vs_ym_sn_end: = To_char (Add_months (To_date (vs_ym_end, ' yyyymm '), -12), ' yyyymm ');

--Deletes the data for a specific condition in the table first.

DELETE from table name WHERE ym = Is_ym;

-then print out the number of rows of records affected using the Put_Line method of the built-in Dbms_output object, which uses a system variable Sql%rowcount

Dbms_output.put_line (' Del last month's record = ' | | sql%rowcount| | ' Article ");
INSERT into table name (Area_code,ym,cmcode,rmb_amt,usd_amt)
SELECT area_code,is_ym,cmcode,sum (Rmb_amt)/10000,sum (Usd_amt)/10000
From bgd_area_cm_m_base_t
WHERE ym >= Vs_ym_beg
and YM <= Vs_ym_end
GROUP by Area_code,cmcode;
Dbms_output.put_line (' ins month record = ' | | sql%rowcount| | ' Article ");
--The traversal cursor is processed and updated to the table. There are several ways to traverse a cursor, and a for statement is one of the more intuitive.

For rec in cur_1 LOOP
UPDATE Table Name
SET rmb_amt_sn = REC.RMB_AMT_SN,USD_AMT_SN = Rec.usd_amt_sn
WHERE Area_code = Rec.area_code
and Cmcode = Rec. Cmcode
and ym = Is_ym;
End LOOP;
COMMIT;

--Error Handling section. Others represents any error except the declaration. SQLERRM is the system built-in variable that holds the details of the current error.

EXCEPTION

When others THEN
Vs_msg: = ' ERROR in xxxxxxxxxxx_p (' | | is_ym| | '): ' | | SUBSTR (sqlerrm,1,500);

ROLLBACK;

--Record the current error in the Log table.

INSERT into Log_info (proc_name,error_info,op_date)
VALUES (' xxxxxxxxxxx_p ', vs_msg,sysdate);
COMMIT;
return;

End;

Oracle Stored Procedure Syntax
1. Judgment statement:
If comparison type then begin end; End If;
Copy Code code as follows:

Create or Replace procedure test (x in number) is
Begin
If x >0 Then
Begin
x: = 0-x;
End
End If;
If x = 0 Then
Begin
x: = 1;
End
End If;
End test;

2, for Loop
For ... in ..... LOOP
--EXECUTE statement
End LOOP;
(1) Loop traversal cursor
Copy Code code as follows:

Create or Replace procedure test () as
Cursor Cursor is select name from student; Name varchar (20);
Begin
For name in cursor LOOP
Begin
Dbms_output.putline (name);
End
End LOOP;
End test;

(2) looping through the array
Copy Code code as follows:

Create or Replace procedure test (Vararray in Mypackage.testarray) as
--(input parameter vararray is a custom array type, as defined by heading 6)
I number;
Begin
I: = 1; --The stored procedure array starts at 1 and differs from languages such as Java, C, and C + +. Because there is no concept of an array in Oracle, the array is actually a
--table, each array element is a record in the table, so traversing the array is equivalent to starting from the first record in the table
For I in 1..vararray.count loop
Dbms_output.putline (' the No. ' | | ' Record in Vararray is: ' | | Vararray (i));
End LOOP;
End test;

3, while Loop
While conditional statement loop
Copy Code code as follows:

Begin
End
End LOOP;
e.g
Create or Replace procedure test (I in number) as
Begin
While I < ten loops
Begin
i:= i + 1;
End
End LOOP;
End test;

4, Array
First, it is clear that there is no concept of an array in Oracle, the array is actually a table (table), and each array element is a record in the table.
When using arrays, users can use an array type that Oracle has already defined, or you can define an array type to suit your needs.
(1) using an Oracle-band array type
x array; --needs to be initialized when used
e.g:
Create or Replace procedure test (y out array) is
x array;
Begin
x: = new Array ();
Y: = x;
End test;
(2) custom array type(When customizing data types, it is recommended to be implemented by creating package to facilitate management)
Create or Replace package MyPackage is
Public type declarations type info are record (name varchar, y number);
Type Testarray is table of the info index by Binary_integer;
--Here you declare a Testarray type data, which is a table that stores the info data type, and Testarray is a list of two fields, one for name and one for Y. It is important to note that the index by Binary_integer for this table is used here, or it can be written directly: type Testarray is
Table of info, if not written, use an array to initialize: Vararray Mypackage.testarray; Vararray: = new Mypackage.testarray ();
End Testarray;
5. Use of CursorsCursor in Oracle is useful for traversing query results in a temporary table. Its related methods and properties are also many, now only used to do one or two introduction:
(1) Cursor-type cursors (cannot be used for parameter passing)
Copy Code code as follows:

Create or Replace procedure test () is
Cusor_1 Cursor is select Std_name from student where ...; --cursor use mode 1 cursor_2 Cursor;
Begin
Select Class_name into cursor_2 from class where ...; How to use--cursor 2
You can use the for x in cursor loop ... end loop; To realize the traversal of the cursor.
End test;
(2) Sys_refcursor-type cursor, which is Oracle's predefined cursor, that can be passed by parameter
Create or Replace procedure test (Rscursor out sys_refcursor) is
Cursor sys_refcursor;
Name Varhcar (20);
Begin
Open cursor for select name from student where ...--sys_refcursor can only be opened and assigned through the Open method
LOOP
Fetch cursor into name--sys_refcursor can only open and traverse exit when cursor%notfound by fetch into; Three status properties can be used in--sys_refcursor:---%notfound (no record information found)%found (locate record information)---%rowcount (and then the row position to which the current cursor points)
Dbms_output.putline (name);
End LOOP;
Rscursor: = cursor;
End test;

Instance
Here is a simple example to apply to the usage of the stored procedure described above:
Now assume that there are two tables, one is the Student performance table (studnet), field: Stdid,math,article,language,music,sport,total,average,step
One is the student's extracurricular performance form (Out_school), field: Stdid,parctice,comment
The total score and average score of each student are calculated automatically through the stored procedure, and if the student gets a rating of a in the extracurricular course, add 20 points to the total score.
Copy Code code as follows:

Create or Replace procedure Autocomputer (step into number) is
Rscursor Sys_refcursor;
Commentarray Mypackage.myarray;
Math number;
article number;
Language number;
Music number;
Sport number;
Total number;
Average number;
stdID varchar (30);
Record Mypackage.stdinfo;
I number;
Begin
I: = 1;
Get_comment (Commentarray); --Invoke a stored procedure named Get_comment () to get students ' extracurricular grading information
OPEN rscursor for select Stdid,math,article,language,music,sport from student t where t.step = step;
LOOP
Fetch rscursor into Stdid,math,article,language,music,sport; Exit when Rscursor%notfound;
Total: = math + article + language + music + sport;
For I in 1..commentarray.count loop
Record: = Commentarray (i);
If stdID = Record.stdid Then
Begin
If record.comment = ' A ' Then
Begin
Total: = total + 20;
Go to Next; --Jump out for loop with Go
End
End If;
End
End If;
End LOOP;
<<continue>> average: = TOTAL/5;
Update Student T set t.total=total and t.average = average where t.stdid = stdID;
End LOOP;
End
End Autocomputer;
--Stored procedures for obtaining student comment information
Create or Replace procedure get_comment (Commentarray out Mypackage.myarray) is
RS Sys_refcursor;
Record Mypackage.stdinfo;
stdID varchar (30);
Comment varchar (1);
I number;
Begin
Open RS for select stdid,comment from Out_school
I: = 1;
LOOP
Fetch RS into stdid,comment; Exit when Rs%notfound;
Record.stdid: = stdID;
Record.comment: = comment;
Recommentarray (i): = record;
I:=i + 1;
End LOOP;
End Get_comment;
--Define array type MyArray
Create or Replace package mypackage is begin
Type Stdinfo is record (stdid varchar (), comment varchar (1));
Type myarray is table of Stdinfo index by Binary_integer;
End MyPackage;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.