Download presentation
Presentation is loading. Please wait.
Published byJeffry Toby Miles Modified over 8 years ago
1
PLSQL Cont…
2
Most Common Oracle Data Types VARCHAR2 –Stores variable-length character data. –Takes a required parameter that specifies a maximum length up to 32,767 bytes. –Does not use a constant or a variable to specify the maximum length; an integer literal must be used. –The maximum width of a VARCHAR2 database column is 4000 bytes
3
Most Common Oracle Data Types CHAR –Stores fixed-length (blank-padded if necessary) character data. –Takes an optional parameter that specifies a maximum length up to 32,767 –Does not use a constant or variable to specify the maximum length; an integer literal must be used. If maximum length is not specified it defaults to 1. –The maximum width of a CHAR database column is 2000 bytes; the default is 1 byte.
4
Most Common Oracle Data Types Number –Stores fixed or floating-point numbers of virtually any size. –Precision is the total number of digits. –Scale determines where rounding occurs. –It is possible to specify precision and omit scale, in which case scale is 0 and only integers are allowed. –Constants or variables cannot be used to specify precision and scale; integer literals must be used. –Maximum precision of a NUMBER value is 38 decimal digits. –Scale can range from -84 to 127
5
Most Common Oracle Data Types Binary Integer –Stores signed integer variables –Compares to the NUMBER data type. BINARY_INTEGER variables are stored in the binary format, which takes less space. –Calculations are faster –Can store any integer value within range. –This data type is used primarily for indexing a PL/SQL table.
6
Most Common Oracle Data Types DATE –Stores fixed-length date values. –Valid dates for DATE variables include January 1, 4712 B.C. to December 31, A.D. 9999. –When stored in a database column, date values include the time of day in seconds since midnight. The date portion defaults to the first day of the current month; the time portion defaults to midnight. –Dates are actually stored in binary format and will be displayed according to the default format.
7
Most Common Oracle Data Types TIMESTAMP –This is a new data type introduced with the Oracle 9i. It is an extension of the DATE data- type. It stores fixed-length date values with precision down to a fraction of a second.
8
Most Common Oracle Data Types BOOLEAN –Stores the values TRUE and FALSE and the non value NULL. Recall that NULL stands for missing, unknown, or inapplicable value. –Only the values TRUE and FALSE and the non value NULL can be assigned to a BOOLEAN variable. –The values TRUE and FALSE cannot be inserted into a database column.
9
Most Common Oracle Data Types Long –Stores variable-length character strings. –The LONG data type is like the VARCHAR2 data type, except that the maximum length of a LONG value is 2 gb. –You cannot select a value longer than 4000 bytes from a LONG column into a LONG variable. –LONG columns can store text, arrays of characters, or even short documents. You can reference LONG columns in UPDATE, INSERT, and (most) SELECT statements, but not in expressions, SQL function calls, or certain SQL clauses, such as WHERE, GROUP BY, and CONNECT BY.
10
Most Common Oracle Data Types LONG RAW –Stores raw binary data of variable length up to 2 gigabytes. LOB (Large Object) –There are four types of LOBS: BLOB, CLOB, NCLOB, and BFILE. These can store binary objects such as image or video files, up to 4 gb in length. –BFILE is a large binary file stored outside the database. The maximum size is 4 gigabytes.
11
Most Common Oracle Data Types ROWID –Internally, every Oracle database table has a ROWID pseudocolumn, which stores binary values called rowids. –Rowids uniquely identify rows and provide the fastest way to access particular rows. –Use thje ROWID data type to store rowids in a readable format. –When you select or fetch a rowid into a ROWID variable, you can use the function ROWIDTOCHAR, which converts the binary value into an 18-byte character string and returns it in that format.
12
Operators (Delimiters): the Separators in an Expression Arithmetic(**,*,/,+,-) Comparison(=,<>,!=,, =,LIKE, IN, BETWEEN, IS NULL) Logical (AND, OR, NOT) String (||,LIKE)
13
Variables Initialization with SELECT INTO In PL/SQL, there are two methods of giving value to variables in a PL/SQL block. –Initialization with the “:=” syntax. –Initialization with a select statement by use of SELECT INTO syntax. A variable that has been declared in the declaration section of the PL/SQL block can later be given a value with a SELECT statement. It is important to note that any single row function can be performed on the item to give the variable a calculated value.
14
Variables Initialization with SELECT INTO DECLARE v_average_cost VARCHAR2(10); BEGIN SELECT TO_CHAR(AVG(cost), ‘$9,999.99’) INTO v_average_cost FROM course; DBMS_OUTPUT.PUT_LINE(‘The average cost of a course in the CTA program is’|| v_average_cost); END;
15
Variables Initialization with SELECT INTO The TO_CHAR function is used to format the cost; in doing this, the number data type is converted to a character data type. Once the variable has a value; it can be displayed to the screen in APEX.
16
Variables Initialization with SELECT INTO It is also possible to insert data into a database table (friends) in PL/SQL
17
Variables Initialization with SELECT INTO DECLARE V_ID FRIENDS.ID%TYPE; V_LNAME FRIENDS.LNAME%TYPE; V_FNAME FRIENDS.FNAME%TYPE; V_ADDRESS FRIENDS.ADDRESS%TYPE; BEGIN SELECT 111, ‘CAPTAIN’, ‘PLANET’, ‘SPARTA’ INTO V_ID, V_LNAME, V_FNAME, V_ADDRESS FROM DUAL; INSERT INTO FRIENDS (ID, LNAME, FNAME, ADDRESS) VALUES (V_ID, V_LNAME, V_FNAME, V_ADDRESS); END;
18
PL/SQL Programming Exercise Create a student table with the following fields: ID, lastname, zip, created_by, created_date, modified_date, registration_date in the Object browser. Then write a PL/SQL block that will insert a new student in the student table. Make sure that you get the highest ID value and then add 1 to it in order to generate a unique ID number.
19
PL/SQL Programming Exercise DECLARE v_max_id number; BEGIN SELECT MAX(student_id) INTO v_max_id FROM student; INSERT into student (student_id, last_name, zip, created_by, created_date, modified_by, modified_date, registration_date ) VALUES (v_max_id + 1, ‘Curly’, 11238, ‘Tops’, ’01-JAN-99’, ‘Tops’,’01-JAN- 99’,’01-JAN-99’); END;
20
Using an Oracle Sequence An Oracle sequence is an Oracle database object that can be used to generate unique numbers. You can use sequences to automatically generate primary key values. Once a sequence is created, you can access its values in SQL statements with these pseudocolumns: CURRVAL – returns the current value of the sequence NEXTVAL – increments the sequence and returns the new value.
21
Drawing numbers from a sequence A sequence value can be inserted directly into a table without first selecting it.
22
SEQUENCE EXAMPLE CREATE TABLE test01(col1 number); CREATE SEQUENCE test_seq INCREMENT BY 5; BEGIN INSERT INTO test01 VALUES(test_seq.NEXTVAL); END; SELECT * FROM test01
23
The IF Statement An IF-THEN statement specifies the sequence of statements to execute only if the condition evaluates to TRUE. When this condition evaluates to FALSE, there is no special action to take except to proceed with the execution of the program.
24
Example of IF-THEN statement DECLARE v_num1 NUMBER := 5; v_num2 NUMBER := 3; v_temp NUMBER; BEGIN IF v_num1 > v_num2 THEN v_temp := v_num1; v_num1 := v_num2; v_num2 := v_temp; END IF; DBMS_OUTPUT.PUT_LINE(‘v_num1 = ’|| v_num1); DBMS_OUTPUT.PUT_LINE(‘v_num2 = ’|| v_num2); END;
25
IF-THEN-ELSE The IF-THEN-ELSE construct should be used when trying to choose between two mutually exclusive actions.
26
IF-THEN-ELSE Example DECLARE v_num1 NUMBER := 0; v_num2 NUMBER; BEGIN IF v_num1 = v_num2 THEN DBMS_OUTPUT.PUT_LINE (‘v_num1 = v_num2’); ELSE DBMS_OUTPUT.PUT_LINE (‘v_num1 != v_num2’); END IF; END;
27
LOOPS The EXIT WHEN statement causes a loop to terminate only if the EXIT WHEN condition evaluates to TRUE. Control is then passed to the first executable statement after the END LOOP statement.
28
LOOP Example DECLARE v_counter BINARY_INTEGER := 0; BEGIN LOOP v_counter := v_counter + 1; DBMS_OUTPUT.PUT_LINE('v_counter=' ||v_counter); IF v_counter = 5 THEN EXIT; END IF; END LOOP; DBMS_OUTPUT.PUT_LINE('Done…'); END;
29
Cursors A cursor is a handle, or a pointer to an area of memory that contains information about an SQL statement that is being processed such as rows returned by a SELECT statement one row at a time. A cursor is named so that it can be referenced.
30
2 types of cursors 1.Implicit cursor – automatically declared by Oracle every time an SQL statement is executed. The user will not be aware of this happening and will not be able to control or process the information in an implicit cursor. 2.Explicit cursor – defined by the program for any query that returns more than one row of data. That means the programmer has declared the cursor within the PL/SQL code block. This declaration allows for the application to sequentially process each row of data as it is returned by the cursor.
31
Processing an Implicit Cursor Any given PL/SQL block issues an implicit cursor whenever an SQL statement is executed, as long as an explicit cursor does not exist for that SQL statement A cursor is automatically associated with every DML (data manipulation language) statement –All update and delete statements have cursors that identify the set of rows that will be affected by the operation. An implicit cursor cannot tell you how many rows were affected by an update. SQL%ROWCOUNT returns numbers of rows updated. –An insert statement needs a place to receive the data that is to be inserted in the database; the implicit cursor fulfills this need.
32
Processing an Implicit Cursor During the processing of an implicit cursor, Oracle automatically performs the OPEN, FETCH and CLOSE operations. The most recently opened cursor is called the SQL% cursor. Oracle automatically associates an implicit cursor with the SELECT INTO statement and fetches the values for the variables, v_first_name and v_last_name. Once the SELECT INTO statement completes, Oracle closes the implicit cursor.
33
Creating a Table for Exercises CREATE TABLE employee( id varchar2(20), lname varchar2(50), fname varchar2(50) ); INSERT INTO employee(id, lname, fname) VALUES (‘01’,’Asterix’,’Gaul’); INSERT INTO employee(id, lname, fname) VALUES (‘02’,’Obelix’,’Gaul’); INSERT INTO employee(id, lname, fname) VALUES (‘123’,’Rodimus’,’Autobot’);
34
Cursor Example BEGIN UPDATE EMPLOYEE SET FNAME = ‘B’ WHERE LNAME LIKE ‘R%’; DBMS_OUTPUT.PUT_LINE(SQL%ROW COUNT); END;
35
Cursor Example DECLARE v_first_name VARCHAR2(35); v_last_name VARCHAR2(35); BEGIN SELECT FNAME, LNAME INTO v_first_name, v_last_name FROM EMPLOYEE WHERE ID = 123; DBMS_OUTPUT.PUT_LINE ('EMPLOYEE NAME: ' || v_first_name || ' ' || v_last_name); EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE ('There is no employee with EMPLOYEE ID 123'); END;
36
Explicit Cursor Must be named in the declare section of the PL/SQL block. Gives more programmatic control to the programmer Oracle interactive series advices us to name a cursor as c_cursorname. By using a c_ in the beginning of the name, it will always clear to you that the name is referencing a cursor.
37
Explicit Cursor When using an explicit cursor, we must do the following. –Declare –Open –Fetch –Close
38
Explicit Cursor Example DECLARE v_eid EMPLOYEE.ID%TYPE; CURSOR c_employee IS SELECT ID FROM EMPLOYEE WHERE ID < 110; BEGIN OPEN c_employee; LOOP FETCH c_employee INTO v_eid; IF c_employee%FOUND THEN DBMS_OUTPUT.PUT_LINE('Just fetched row' || TO_CHAR(c_employee%ROWCOUNT)|| 'EMPLOYEE ID:'|| v_eid); ELSE EXIT; END IF; END LOOP; CLOSE c_employee; END;
39
Explicit Cursor In the declaration section, we defined cursor named c_employee, based on the EMPLOYEE table such that the ID < 110. This returns the field ID based on the cursor. To open the cursor, we just say open c_employee
40
Explicit Cursor To fetch the contents of the cursor, we declare a FETCH. The FETCH command is used to retrieve one row at a time from the active set. This is generally done inside a loop. The values of each row in the active set can then be stored into the corresponding variables or PL/SQL record one at a time, performing operations on each on successively.
41
Explicit Cursor After each FETCH, the active set pointer is moved forward to the next row. Thus, each fetch will return successive rows of the active set, until the entire set is returned. The last FETCH will not assign values to the output variables; they will still contain their prior values.
42
Explicit Cursor Attributes Cursor AttributeSyntaxExplanation %NOTFOUNDCursor_name%NOTFOUNDA boolean attribute that returns TRUE if the previous FETCH did not return a row, and FALSE if it did. %FOUNDCursor_name%foundA boolean attribute that returns TRUE if the previous FETCH returned a row, and FALSE if it did not. %ROWCOUNTCursor_name%ROWCOUNT# of records fetched from a cursor at that point in time %ISOPENCursor_name%ISOPENA boolean attribute that returns TRUE if cursor is open, FALSE if it is not.
43
A cursor that returns the first five employee names from the employee table DECLARE CURSOR c_employee_name IS SELECT FNAME, LNAME FROM EMPLOYEE WHERE rownum <= 5; vr_employee_name c_employee_name%ROWTYPE; BEGIN OPEN c_employee_name; LOOP FETCH c_employee_name INTO vr_employee_name; EXIT WHEN c_employee_name%NOTFOUND; END LOOP; CLOSE c_employee_name; DBMS_OUTPUT.PUT_LINE('Employee name: ' || vr_employee_name.FNAME || vr_employee_name.LNAME); END;
44
Using cursor for Loops and Nesting Cursors An alternative method of handling cursors Here, the process of opening, fetching, and closing is handled implicitly Makes the blocks much simpler to code and easier to maintain Opening fetching and closing is handled implicitly Makes the blocks much simpler to code and easier to maintain
45
Make a table to illustrate the examples Create table table_log(description VARCHAR2 (250));
46
PROCEDURES A procedure is a module performing one or more actions; it does not need to return any value. A procedure may have 0 to many parameters. Every procedure has two parts: The header portion, which comes before AS (sometimes you will see IS – they are interchangeable), keyword and the body which is everything after the IS keyword.
47
PROCEDURES The word REPLACE s optional. When the word replace is not used in the header of the procedure, in order to change the code in the procedure, the procedure must be dropped and then re-created. Since it is very common to change the code of the procedure, especially when it is under development, it is strongly recommended to use the OR REPLACE option
48
Procedure Syntax CREATE OR REPLACE PROCEDURE name AS [local declarations] BEGIN executable statements [Exception handlers] END [name];
49
FUNCTIONS Functions are another type of stored code and are very similar to procedures. The significant difference is that a function is a PL/SQL block that returns a single value. Functions can accept one many, or no parameters, but a function must have a return clause in the executable section of the function. A function is not a stand-alone executable in the way that a procedure is: It must be used in some context. You can think of it as a sentence fragment.
50
FUNCTIONS A function has output that needs to be assigned to a variable or it can be used in a SELECT statement. The function must have a RETURN value declared in the header, and it must return values for all varying possible execution streams. There may be more than one RETURN statement.
51
Function Example CREATE OR REPLACE FUNCTION show_address(i_ID EMPLOYEE.ID%TYPE) RETURN varchar2 AS v_address varchar2(50); BEGIN SELECT ADDRESS INTO v_address FROM EMPLOYEE WHERE ID = i_ID; RETURN v_address; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN('The employee is not in the database'); WHEN OTHERS THEN RETURN ('Error in running show_address'); END;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.