Basic Oracle Stored Procedure syntax

Source: Internet
Author: User
Tags rowcount
Document directory
  • Stored Procedure
  • Stored Procedure creation Syntax:
Stored Procedure

1 create or replace procedure stored procedure name

2 is

3 begin

4 null;

5 end;

Row 1:

Create or replace procedure is an SQL statement that notifies the Oracle database to create a stored procedure called skeleton, and overwrites it if it exists;

Row 2:

The is keyword indicates that a PL/SQL body will be followed.

Row 3:

The begin keyword indicates the start of the PL/SQL body.

Row 4:

The null PL/SQL statement indicates that nothing is done. This statement cannot be deleted because at least one sentence is required in the PL/SQL body;

Row 5:

The end keyword indicates the end 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 );

Begin

Select count (*) into variable 1 from Table A where column name = param1;

If (condition) then

Select column name into variable 2 from Table A where column name = param1;

Dbms_output. Put_line ('print info ');

Elsif (Judgment condition) then

Dbms_output. Put_line ('print info ');

Else

Raise Exception name (no_data_found );

End if;

Exception

When others then

Rollback;

End;

Note:

1. stored procedure parameters do not have a value range. In indicates input, and out indicates output.

Type can use the legal type in any oracle.

2. The variable has a value range followed by a semicolon

3. Use the count (*) function to determine whether the operation record exists before determining the statement.

4. Select... Into... Assign values to variables

5. If an exception is thrown in the code, use raise + Exception name.

Create or replace procedure stored procedure name
(

-- Define parameters
Is_ym in char (6 ),

The_count out number,
)
As
-- Define variables
Vs_msg varchar2 (4000); -- error message variable
Vs_ym_beg char (6); -- start month
Vs_ym_end char (6); -- end month
Vs_ym_sn_beg char (6); -- start month of the same period
Vs_ym_sn_end char (6); -- end month of the same period

-- Define a cursor (simply put, a result set that can be traversed)

Cursor cur_1 is
Select...
From...
Where...
Group ...;

Begin

-- Use the input parameter to assign the initial value to the variable, and use the substr to_char add_months of oralce.

To_date and other 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, 'yyymm'),-12), 'yyymm ');
Vs_ym_sn_end: = to_char (add_months (to_date (vs_ym_end, 'yyymm'),-12), 'yyymm ');

-- Delete data with specific conditions in the table first.

Delete from table name where ym = is_ym;

-- Then use the put_line method of the built-in dbms_output object to print the number of affected records. One system variable SQL % rowcount is used.

Dbms_output.put_line ('del last month record = '| SQL % rowcount |' bar ');

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 Record of the current month = '| SQL % rowcount |' bar ');

-- The traversal cursor is processed and updated to the table. You can use the for statement to traverse a cursor in several ways.

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 indicates any errors except declarations. Sqlerrm is a built-in variable that saves detailed information about the current error.

Exception

When others then
Vs_msg: = 'error in xxxxxxxxxxx_p ('| is_ym |'): '| substr (sqlerrm, 1,500 );

Rollback;

-- Record the current error to 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 then begin end; end if;

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 the statement

End loop;

(1) looping cursor

Create or replace procedure Test ()

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) traverse arrays cyclically

Create or replace procedure Test (vararray in mypackage. testarray)

-- (Input parameter vararray
Is a custom array type. For the definition method, see heading 6)

I number;

Begin

I: = 1; -- the Stored Procedure array is from 1
And Java
, C
And C ++. Because in Oracle
There is no array concept in this article. arrays are actually

-- Table ),
Each array element is a record in the Table. Therefore, when traversing the array, it is equivalent to traversing from the first record in the table.

For I in 1 .. vararray. Count Loop

Dbms_output.putline ('the No. '| I | 'record in vararray is:' | vararray (I ));

End loop;

End test;

3. While Loop

While Condition Statement Loop

Begin

End;

End loop;

E. g

Create or replace procedure Test (I in number)

Begin

While I <10 Loop

Begin

I: = I + 1;

End;

End loop;

End test;

4. Array

First, let's clarify a concept: Oracle does not have an array. arrays are actually a table ),
Each array element is a record in the table.

When using arrays, you can use the array types defined in Oracle, or you can define the array types as needed.

(1) Use Oracle
Built-in array type

X array; -- Initialization is required for use.

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 (
We recommend that you create a package to customize the data type for ease of management)

Create or replace package mypackage is

Public type declarations type info is record (name varchar (20), y number );

Type testarray is table of info index by binary_integer;

-- A testarray is declared here.
In fact, it is a storage info
Data Type table
And testarray.
Is a table with two fields: Name
, One is Y
. Note that index by binary_integer is used here.
Compile the table
Can also be written as: Type testarray is

Table of info. If no data is written, Initialization is required when array is used: vararray mypackage. testarray; vararray: = new mypackage. testarray ();

End testarray;

5. Use Oracle for cursors
Cursor is very useful in traversing the query results in the temporary table. There are also many related methods and attributes. Currently, we will only introduce the common usage:

(1) cursor type cursor (
Cannot be used for parameter transfer)

Create or replace procedure Test () is

Cusor_1 cursor is select std_name from student where...; -- cursor
Method 1 cursor_2 cursor;

Begin

Select class_name into cursor_2 from class where...; -- cursor
Method 2

You can use for X in cursor loop... end loop;
To implement
Traversal

End test;

(2) sys_refcursor type cursor, which is an oracle
Parameters can be passed with pre-defined cursors

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 use open
Method to open and assign values

Loop

Fetch cursor into name -- sys_refcursor
You can only open and traverse through fetch.
Exit when cursor % notfound; -- sys_refcursor
Three State attributes can be used: --- % notfound (
Record information not found) % found (
Locate record information) --- % rowcount (
Then the row position pointed to by the current cursor)

Dbms_output.putline (name );

End loop;

Rscursor: = cursor;

End test;

Instance

The following is a simple example to apply the usage of the above stored procedure:

Assume that two tables exist, one of which is studnet)
, Field: stdid, math, article, language, music, sport, total, average, step

One is the out-of-class student quota table (out_school) with the following fields: stdid, parctice, and comment.

The storage process automatically calculates the total score and average score of each student.
Add 20 to the total score.
Points.

Create or replace procedure autocomputer (step in 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); -- call get_comment ()
To obtain the student's out-of-class rating 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; -- use go
Jump out of
Loop

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 procedure 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 the array type myarray

Create or replace package mypackage is begin

Type stdinfo is record (stdid varchar (30), comment varchar (1 ));

Type myarray is table of stdinfo index by binary_integer;

End mypackage;

Byebye

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.