Introduction to PL/SQL
PL/SQL is procedural programming language that uses sequencial instructions to process data. SQL commands can be used withing PL/SQL to intract with the database. PL/SQL is also part of the Oracle development enviroment which can be stored directly into an Oracle database. The syntax to create PL/SQL is as follows: DECLARE declare here all the varibales BEGIN write here all the program statements EXCEPTION write here all the error-handling statements END;
Variables are declared in the program declaration section using PL/SQL variables types, which are similar to SQL variables types. All the program statements are defined in the BEGIN section of the program and EXCEPTION section is for error handling statements. The following are list of PL/SQL variable types that are also SQL variable types:
Variable type | Description | Example |
VARCHAR2 | Variable-lenth character strings | name VARCHAR2(35); |
CHAR | Fixed-lenth character string | middle_init VARCHAR2(1); |
DATE | Date type | birth_date DATE; |
NUMBER | Floating, fixed, or integer numbers | price NUMBER(4); |
LONG | Long text up to 32760 bytes | comment LONG; |
BINARY_INTEGER | Integer number | counter BINARY_INTEGER; |
| INTEGER | Integer number | counter INTEGER; |
| INT | Integer number | counter INT; |
| SMALLINT | Integer number | counter SMAILLINT; |
| DEC | Floating point number | price DEC; |
DECIMAL | Floating point number | price DECIMAL; |
DOUBLE | Floating point number | price DOUBLE; |
PRECISION | Floating point number | price PRECISION; |
NUMERIC | Floating point number | price NUMERIC; |
REAL | Floating point number | price REAL; |
BOOLEAN | True or false | Is_customer BOOLEAN; |
LOB | large objects | product_image LOB; |
The following is simple PL/SQL program that calculates some one's age:
DECLARE name VARCHAR2(35); birth_date DATE; current_date DATE; age NUMBER(2);
BEGIN
name := 'Joe doe'; birth_date := TO_DATE('05/01/1980','MM/DD/YYYY'); current_date := SYSDATE; age := TRUNC((current_date - birth_date)/365.25, 0);
DBMS_OUTPUT.PUT_LINE('Name: '||name ||' Age: '|| age);
END; /
| := is an assignment sign for PL/SQL and = is comparison sign. TO_DATE is a function that converts character string to internal date format [see variable types for more conversion functions] and TRUNC is another function that truncates the result to specified precision points. Date subtracted date will give you number of days, 365.25 is divided by to convert days into years. DBMS_OUTPUT.PUT_LINE() displays the program output whether it's strings or variables. SYSDATE is current system date. |
Bellow is picture of this example on sql plus server: Before you insert PL/SQL code into SQL Server, you have to set up the server output which is the space to display code result. Type this command before inserting the code; SET SERVEROUTPUT ON SIZE 4000. |