Distributed Database Applications
Download
Report
Transcript Distributed Database Applications
Distributed Database
Applications
COSC 5050
Week Two
Outline
Data types and composite structures
Working with program data
Strings
Numbers
Dates and Timestamps
Records and Collections
Miscellaneous datatypes
Webster University
Distributed Database Applications
Jiangping Wang
Program Data
Naming rules
Up to 30 characters
Start with a letter
Can have letters, numerals, $, #, and _
Case-insensitive
Webster University
Distributed Database Applications
Jiangping Wang
Oracle Predefined Datatypes
CHAR(n)
VARCHAR2(n)
NUMBER(n)
NUMBER(n, m)
PLS_INTEGER
BOOLEAN
DATE
Webster University
Distributed Database Applications
Jiangping Wang
Groups of Data Types
Scalar types – predefined data types
%TYPE attributes
Supports types that may be derived from a
database table definition
Include %TYPE and %ROWTYPE
Composite types
May be created from TABLES and RECORDS
%ROWTYPE
These are composite types with a structure that is
derived from a base table or a cursor declaration
Webster University
Distributed Database Applications
Jiangping Wang
Declaring Program Data
Variable
l_total_count NUMBER;
l_dollar_amount NUMBER (10, 2);
l_right_now DATE NOT NULL DEFAULT SYSDATE;
l_favorite_flavor VARCHAR2(100)
:= ‘Anything with chocolate, actually';
TYPE list_of_books_t IS TABLE OF
book%ROWTYPE INDEX BY BINARY_INTEGER;
oreilly_oracle_books list_of_books_t;
Constant
l_curr_year CONSTANT PLS_INTEGER
:= TO_NUMBER(TO_CHAR(SYSDATE, ‘YYYY’));
l_author CONSTANT VARCHAR2(100)
DEFAULT ‘Bill Pribyl’;
Webster University
Distributed Database Applications
Jiangping Wang
Anchored Declarations
Scalar anchoring
Based on column or other scalar variable
%TYPE
l_company_id company.company_id%TYPE
emp_id emp.empno%TYPE
new_emp emp_id%TYPE
Record anchoring
Based on table or explicit cursor
%ROWTYPE
l_book book%ROWTYPE;
l_employee employee%rowtype;
l_employee emp_cur%rowtype;
Benefits of anchored declarations
Webster University
Distributed Database Applications
Jiangping Wang
Anchored Declarations
Column%TYPE
create or replace procedure charge is
-- customer.account column is defined as number(7,2)
balance customer.account%type;
begin
balance := 50.12;
balance := balance * 1.12; -- what is the value?
dbms_output.put_line('balance is : ' || balance);
end charge;
/
Webster University
Distributed Database Applications
Jiangping Wang
Anchored Declarations
declare
l_employee employee%rowtype;
begin
select * into l_employee from employee
where ssn = '600000001';
dbms_output.put_line(l_employee.fname || ' ' ||
l_employee.lname);
end;
declare
cursor emp_cur is
select fname, lname from employee
where ssn = '600000001';
l_employee emp_cur%rowtype;
begin
open emp_cur;
fetch emp_cur into l_employee;
dbms_output.put_line(l_employee.fname || ' ' ||
l_employee.lname);
close emp_cur;
end;
Webster University
Distributed Database Applications
Jiangping Wang
Programmer Defined Subtypes
Define subtypes or aliases of predefined
datatypes
SUBTYPE subtype_name IS base_type
SUBTYPE POSITIVE IS BINARY_INTEGER
RANGE 1 .. 2147483647;
SUBTYPE FLOAT IS NUMBER;
SUBTYPE big_string IS VARCHAR2(32767);
Webster University
Distributed Database Applications
Jiangping Wang
Datatype Conversions
Implicit conversation vs. explicit
conversion
DECLARE
a_number
Figure 7-2, page 184
Implicit conversions
Table 7-1, page 185
NUMBER;
BEGIN
a_number := '125';
END;
The built-in conversion functions
TO_CHAR( )
TO_NUMBER( )
TO_DATE( )
Webster University
Distributed Database Applications
Jiangping Wang
Implicit Conversation
Webster University
Distributed Database Applications
Jiangping Wang
Strings
CHAR(n)
feature_name CHAR(100);
VARCHAR2(n)
small_string VARCHAR2(4);
line_of_text VARCHAR2(2000);
Fixed-length
Variable-length
Database character set
CHAR
VARCHAR2
National character set
NCHAR
NVARCHAR2
Webster University
Distributed Database Applications
Jiangping Wang
String Subtypes
PL/SQL subtypes and their equivalents
Table 8-1, page 194
Subtype
Equivalent PL/SQL type
CHAR VARYING
VARCHAR2
CHARACTER
CHAR
CHARACTER VARYING
VARCHAR2
NATIONAL CHAR
NCHAR
NATIONAL CHAR VARYING
NVARCHAR2
NATIONAL CHARACTER
NCHAR
NATIONAL CHARACTER VARYING
NVARCHAR2
NCHAR VARYING
NVARCHAR2
STRING
VARCHAR2
VARCHAR
VARCHAR2
Webster University
Distributed Database Applications
Jiangping Wang
Empty Strings are NULL
DECLARE
empty_varchar2 VARCHAR2(10) := '';
empty_char CHAR(10) := '';
BEGIN
IF empty_varchar2 IS NULL THEN
DBMS_OUTPUT.PUT_LINE('empty_varchar2 is NULL');
END IF;
IF '' IS NULL THEN
DBMS_OUTPUT.PUT_LINE(''''' is NULL');
END IF;
IF empty_char IS NULL THEN
DBMS_OUTPUT.PUT_LINE('empty_char is NULL');
ELSIF empty_char IS NOT NULL THEN
DBMS_OUTPUT.PUT_LINE('empty_char is NOT NULL');
END IF;
END;
/
Webster University
Distributed Database Applications
Jiangping Wang
String Comparisons
DECLARE
company_name CHAR(30) := 'Feuerstein and Friends';
char_parent_company_name CHAR(35) := 'Feuerstein and Friends';
varchar2_parent_company_name VARCHAR2(35) := 'Feuerstein and Friends';
BEGIN
--Compare two CHARs, so blank-padding is used
IF company_name = char_parent_company_name THEN
DBMS_OUTPUT.PUT_LINE ('first comparison is TRUE');
ELSE
DBMS_OUTPUT.PUT_LINE ('first comparison is FALSE');
END IF;
--Compare a CHAR and a VARCHAR2, so nonblank-padding is used
IF company_name = varchar2_parent_company_name THEN
DBMS_OUTPUT.PUT_LINE ('second comparison is TRUE');
ELSE
DBMS_OUTPUT.PUT_LINE ('second comparison is FALSE');
END IF;
END;
/ Webster University
Distributed Database Applications
Jiangping Wang
String Functions
ASCII, CHR
CHR(64)
-- which is ‘@’
INSTR
DECLARE
company_name VARCHAR2(30) := 'Microsoft Inc.';
BEGIN
DBMS_OUTPUT.PUT_LINE(INSTR (company_name, 'Inc'));
END;
LENGTH
LENGTH(‘abcd’) -> 4
LENGTH(NULL) -> NULL
SUBSTR, LOWER, UPPER, INITCAP
CONCAT
begin
dbms_output.put_line('abc' || 'def' || 'ghi');
dbms_output.put_line(concat(concat('abc','def'),'ghi'));
end;
Webster University
Distributed Database Applications
Jiangping Wang
Numbers
NUMBER
NUMBER(precision, scale)
NUMBER(9,2)
NUMBER(9,11)
NUMBER(9,-11)
Rounding of values (page 234)
PLS_INTEGER
Uses native machine arithmetic
BINARY_INTEGER
Equivalent to PLS_INTEGER (since 10g)
Uses platform independent library code (before 10g)
Numeric subtypes (page 246)
Webster University
Distributed Database Applications
Jiangping Wang
Numeric Subtypes
Webster University
Distributed Database Applications
Jiangping Wang
Numeric Functions
TO_NUMBER
begin
dbms_output.put_line(to_number('12345.67'));
end;
TO_CHAR
DECLARE
b VARCHAR2(30);
BEGIN
b := TO_CHAR(123456789.01,'L999G999G999D99');
DBMS_OUTPUT.PUT_LINE(b);
END;
ABS, CEIL, FLOOR, POWER, SQRT
Webster University
Distributed Database Applications
Jiangping Wang
Date and Time
DATE
TIMESTAMP
TIMESTAMP WITH TIME ZONE
TIMESTAMP WITH LOCAL TIME ZONE
Webster University
Distributed Database Applications
Jiangping Wang
Date and Time
Effect of different datetime datatypes
Figure 10-1, page 269
Webster University
Distributed Database Applications
Jiangping Wang
Date and Time
Comparison of functions that return current
data and time
Table 10-1, page 272
Function
Time zone
Datatype returned
CURRENT_DATE
Session
DATE
CURRENT_TIMESTAMP
Session
TIMESTAMP WITH TIME ZONE
LOCALTIMESTAMP
Session
TIMESTAMP
SYSDATE
Server
DATE
SYSTIMESTAMP
Server
TIMESTAMP WITH TIME ZONE
Webster University
Distributed Database Applications
Jiangping Wang
Date and Time
DECLARE
today_date DATE := SYSDATE;
BEGIN
dbms_output.put_line(TO_CHAR(today_date));
END;
Format date and time
TO_DATE(’12/31/2003’); -- ?
TO_CHAR()
Webster University
Distributed Database Applications
Jiangping Wang
Date/Time Format
To display, the Date value is converted from
the internal format to a printable string
Oracle's default format for Date is
DD-MON-YY
To covert explicitly
TO_CHAR(value, 'MM/DD/YYYY')
Change the default Date format
alter session set NLS_DATE_FORMAT='MM/DD/YYYY';
Webster University
Distributed Database Applications
Jiangping Wang
Date/Time Format
Webster University
Distributed Database Applications
Jiangping Wang
TIMESTAMP
TIMESTAMP datatypes
TIMESTAMP
DECLARE
today_date TIMESTAMP := SYSDATE;
BEGIN
dbms_output.put_line(TO_CHAR(today_date));
END;
DECLARE
the_day date := to_date('22-MAR-2006');
BEGIN
dbms_output.put_line(the_day);
END;
Webster University
Distributed Database Applications
Jiangping Wang
Date/Time Functions
ADD_MONTHS function
BEGIN
dbms_output.put_line(add_months(sysdate, 3));
dbms_output.put_line(add_months(sysdate, -3));
END;
LAST_DAY function
DECLARE
the_day date := to_date('28-FEB-2010');
BEGIN
dbms_output.put_line(last_day(the_day));
dbms_output.put_line(last_day(sysdate));
END;
MONTHS_BETWEEN function
DECLARE
the_day date := to_date('28-FEB-2010');
BEGIN
dbms_output.put_line(months_between(sysdate, the_day));
END;
Webster University
Distributed Database Applications
Jiangping Wang
Records
Records are composite structures
Similar to a row in a database table
Record allow you to select specific
columns from one or more tables into
single data structure
Webster University
Distributed Database Applications
Jiangping Wang
Declaring Records
Table-based record
one_book books%rowtype;
l_employee employee%rowtype;
Cursor-based record
cursor my_books_cur is
select * from books
where author like 'feuerstein%';
one_sf_book my_books_cur%rowtype;
cursor emp_cur is
select fname, lname from employee
where ssn = '600000001';
l_employee emp_cur%rowtype;
Webster University
Distributed Database Applications
Jiangping Wang
Declaring Records
Programmer-defined record
TYPE book_info_rt IS RECORD (
author books.author%TYPE,
category VARCHAR2(100),
total_page_count POSITIVE);
steven_as_author book_info_rt; -- not %ROWTYPE
Webster University
Distributed Database Applications
Jiangping Wang
Programmer-Defined Record
TYPE customer_sales_rectype IS RECORD
(customer_id NUMBER (5),
customer_name customer.name%TYPE,
total_sales NUMBER (15,2)
);
prev_customer_sales_rec customer_sales_rectype;
top_customer_rec customer_sales_rectype;
Webster University
Distributed Database Applications
Jiangping Wang
Working with Records
DECLARE
TYPE customer_sales_rectype IS RECORD
(customer_id NUMBER (5),
customer_name customer.name%TYPE,
total_sales NUMBER (15,2)
);
top_customer_rec customer_sales_rectype;
BEGIN
SELECT customer_id, name, SUM(total_sales)
INTO top_customer_rec
FROM cust_sales_roundup
WHERE sold_on < ADD_MONTHS (SYSDATE, -3)
GROUP BY customer_id, name;
END;
Webster University
Distributed Database Applications
Jiangping Wang
Record-Level Operations
Copy contents of one record to another
Assign a value of NULL to a record with
a simple assignment
Define and pass record as an argument
in a parameter list
RETURN a record back through the
interface of a function
Insert into a database table with record
Since Oracle9i Database Release 2
Webster University
Distributed Database Applications
Jiangping Wang
Record-Level Operations
Cannot use the IS NULL syntax to see if
all fields have NULL values
Apply IS NULL operator to each field
individually
Cannot compare two records
Compare each field individually
Webster University
Distributed Database Applications
Jiangping Wang
Field-Level Operations
DECLARE
TYPE phone_rectype IS RECORD
(area_code VARCHAR2(3),
exchange VARCHAR2(3),
phone_number VARCHAR2(4)
);
TYPE contact_set_rectype IS RECORD
(day_phone# phone_rectype,
eve_phone# phone_rectype,
fax_phone# phone_rectype
);
auth_rep_info_rec contact_set_rectype;
BEGIN
...
auth_rep_info_rec.fax_phone#.area_code :=
auth_rep_info_rec.day_phone#.area_code;
...
END;
Webster University
Distributed Database Applications
Jiangping Wang
Comparing Records
To test for record equality, each field
has to be compared individually
Compare for NULL
(first_book.favorite_author =
second_book.favorite_author
OR
(first_book.favorite_author IS NULL AND
second_book.favorite_author IS NULL)
Webster University
Distributed Database Applications
Jiangping Wang
Collections
A collection is a list of items
One dimensioned array
Define a particular structure using the
TYPE statement – datatype
Declare the actual collection based on
the table type
Types of collections
Associative arrays
Nested tables
VARRAYs
Webster University
Distributed Database Applications
Jiangping Wang
Collections
Associative arrays
Single-dimensional, unbounded, sparse
collections of homogeneous elements
PL/SQL only
Nested tables
Single-dimensional, unbounded collections
of homogeneous elements
Can be sparse
VARRAYs
Single-dimensional collections of
homogeneous elements
always bounded and never sparse
Webster University
Distributed Database Applications
Jiangping Wang
Collections
declare
type list_of_dates_t is table of date;
type list_of_names_t is table of varchar2(100)
index by pls_integer;
birthdays list_of_dates_t := list_of_dates_t();
happyfamily list_of_names_t;
begin
birthdays.extend;
birthdays(1) := '23-sep-1958';
birthdays.extend;
birthdays(2) := '1-oct-1968';
happyfamily(1) := 'Steven';
happyfamily(2) := 'Veva';
happyfamily(4) := 'Chris';
happyfamily(5) := 'Eli';
dbms_output.put_line(birthdays.count);
dbms_output.put_line(happyfamily.first);
end;
Webster University
Distributed Database Applications
Jiangping Wang
Collections
DECLARE
CURSOR emp_cur IS
SELECT * FROM employee;
TYPE emp_data_type IS TABLE OF emp_cur%ROWTYPE
INDEX BY PLS_INTEGER;
emp_table emp_data_type;
i pls_integer;
emp_id employee.ssn%type;
BEGIN
i := 1;
OPEN emp_cur;
LOOP
FETCH emp_cur INTO emp_table(i);
EXIT WHEN emp_cur%NOTFOUND;
dbms_output.put_line(emp_table(i).lname);
i := i + 1;
END LOOP;
CLOSE emp_cur;
dbms_output.put_line('Number of employee: ' || emp_table.count);
END;
Webster University
Distributed Database Applications
Jiangping Wang
Miscellaneous Datatypes
Boolean datatype
ROWID and UROWID
LOB datatype
XMLType datatype
Webster University
Distributed Database Applications
Jiangping Wang
Boolean Datatype
DECLARE
b BOOLEAN := FALSE;
BEGIN
IF b THEN
dbms_output.put_line('true');
ELSE
dbms_output.put_line('false');
END IF;
END;
/
Oracle RDBMS does not support a Boolean datatype
Webster University
Distributed Database Applications
Jiangping Wang
UROWID & ROWID Datatype
DECLARE
employee_rowid urowid;
emp_fname varchar2(20);
BEGIN
SELECT rowid, fname
INTO employee_rowid, emp_fname
FROM employee
WHERE lname = 'Letterman';
dbms_output.put_line(employee_rowid);
dbms_output.put_line(emp_fname);
END;
/
Webster University
Distributed Database Applications
Jiangping Wang
LOB Datatype
BFILE
File locator point to an operating system
file outside the database
BLOB, CLOB, NCLOB
LOB locator point to a large object stored
inside the database
Webster University
Distributed Database Applications
Jiangping Wang
XMLType Datatype
Use XMLType to define database
columns and PL/SQL variables
Methods defined on XMLType
Instantiate new XMLType values
Extract portions of an XML document
Manipulate the contents of an XML
document
Webster University
Distributed Database Applications
Jiangping Wang
XMLType Type
CREATE TABLE falls (
fall_id NUMBER,
fall XMLType
);
INSERT INTO falls VALUES (1, XMLType.CreateXML(
'<?xml version="1.0"?>
<fall>
<name>Munising Falls</name>
<county>Alger</county>
<state>MI</state>
<url>http://michiganwaterfalls.com</url>
</fall>')
);
SELECT fall_id
FROM falls f
WHERE f.fall.existsNode('/fall/url') > 0;
Webster University
Distributed Database Applications
Jiangping Wang
Homework
Create an anonymous PL/SQL block to
retrieve data from above database table
into a record and display a detailed report
of records.
Create an anonymous PL/SQL block to
retrieve data from above database table
into a collection and display a detailed
report of records.
Create a simple procedure in DB2 to test if
empty strings are null in IBM DB2.
Lab activities
Webster University
Distributed Database Applications
Jiangping Wang