SLIDE 38 Database Programming in SQL/ORACLE
Procedures and Functions
- Invocation of procedures in a PL/SQL body:
<procedure> (arg1,...,argn);
(if a formal parameter is declared as OUT or INOUT, the respective argument must be a variable)
- Invocation of procedures in SQLPlus:
execute
<procedure> (arg1,...,argn);
- Usage of functions in PL/SQL:
...
<function> (arg1,...,argn) ...
as in other programming languages. The system-owned table DUAL is commonly used for displaying thr return value of functions: SELECT
<function> (arg1,...,argn)
FROM DUAL;
PL/SQL 148 Database Programming in SQL/ORACLE
Example: Procedure
- Simple procedure: PL/SQL-Body contains only SQL
statements Information about countries is distributed over several relations. CREATE OR REPLACE PROCEDURE InsertCountry (name VARCHAR2, code VARCHAR2, area NUMBER, pop NUMBER, gdp NUMBER, inflation NUMBER, pop_growth NUMBER) IS BEGIN INSERT INTO Country (Name,Code,Area,Population) VALUES (name,code,area,pop); INSERT INTO Economy (Country,GDP,Inflation) VALUES (code,gdp,inflation); INSERT INTO Population (Country,Population_Growth) VALUES (code,pop_growth); END; / EXECUTE InsertCountry (’Lummerland’, ’LU’, 1, 4, 50, 0.5, 0.25);
PL/SQL 149 Database Programming in SQL/ORACLE
Example: Function
- Simple function: population density of a country
CREATE OR REPLACE FUNCTION Density (arg VARCHAR2) RETURN number IS temp number; BEGIN SELECT Population/Area INTO temp FROM Country WHERE code = arg; RETURN temp; END; / SELECT Density(’D’) FROM dual;
PL/SQL 150 Database Programming in SQL/ORACLE
PL/SQL-Variables and Data Types.
Declaration of the PL/SQL Variables in the declaration section:
<variable> <datatype> [NOT NULL] [DEFAULT <value>];
. . .
<variable> <datatype> [NOT NULL] [DEFAULT <value>];
Simple data types: BOOLEAN: TRUE, FALSE, NULL, BINARY_INTEGER, PLS_INTEGER: Signed integers, NATURAL, INT, SMALLINT, REAL, . . . : Numerical data types. amount NUMBER DEFAULT 0; name VARCHAR2(30);
PL/SQL 151