distributed database applications cosc 5050 week two
TRANSCRIPT
Distributed Database Applications
COSC 5050Week Two
Jiangping WangWebster University Distributed Database Applications
Outline
Data types and composite structuresWorking with program dataStringsNumbersDates and TimestampsRecords and CollectionsMiscellaneous datatypes
Jiangping WangWebster University Distributed Database Applications
Program Data
Naming rulesUp to 30 charactersStart with a letterCan have letters, numerals, $, #, and _Case-insensitive
Jiangping WangWebster University Distributed Database Applications
Oracle Predefined Datatypes
CHAR(n)
VARCHAR2(n)
NUMBER(n)
NUMBER(n, m)
PLS_INTEGER
BOOLEAN
DATE
Jiangping WangWebster University Distributed Database Applications
Groups of Data TypesScalar types – predefined data types%TYPE attributes
Supports types that may be derived from a database table definitionInclude %TYPE and %ROWTYPE
Composite typesMay be created from TABLES and RECORDS
%ROWTYPEThese are composite types with a structure that is derived from a base table or a cursor declaration
Jiangping WangWebster University Distributed Database Applications
Declaring Program DataVariable
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;
Constantl_curr_year CONSTANT PLS_INTEGER := TO_NUMBER(TO_CHAR(SYSDATE, ‘YYYY’));
l_author CONSTANT VARCHAR2(100) DEFAULT ‘Bill Pribyl’;
Jiangping WangWebster University Distributed Database Applications
Anchored DeclarationsScalar anchoring
Based on column or other scalar variable%TYPEl_company_id company.company_id%TYPEemp_id emp.empno%TYPEnew_emp emp_id%TYPE
Record anchoringBased on table or explicit cursor%ROWTYPEl_book book%ROWTYPE;l_employee employee%rowtype;l_employee emp_cur%rowtype;
Benefits of anchored declarations
Jiangping WangWebster University Distributed Database Applications
Anchored Declarations
Column%TYPE
create or replace procedure charge is-- customer.account column is defined as number(7,2)balance customer.account%type;
beginbalance := 50.12;balance := balance * 1.12; -- what is the value?dbms_output.put_line('balance is : ' || balance);
end charge;/
Jiangping WangWebster University Distributed Database Applications
Anchored Declarationsdeclare
l_employee employee%rowtype;begin
select * into l_employee from employeewhere ssn = '600000001';dbms_output.put_line(l_employee.fname || ' ' || l_employee.lname);
end;
declarecursor emp_cur is
select fname, lname from employeewhere 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;
Jiangping WangWebster University Distributed Database Applications
Programmer Defined Subtypes
Define subtypes or aliases of predefined datatypes
SUBTYPE subtype_name IS base_typeSUBTYPE POSITIVE IS BINARY_INTEGER
RANGE 1 .. 2147483647;
SUBTYPE FLOAT IS NUMBER;
SUBTYPE big_string IS VARCHAR2(32767);
Jiangping WangWebster University Distributed Database Applications
Datatype Conversions
Implicit conversation vs. explicit conversion
Figure 7-2, page 184Implicit conversions
Table 7-1, page 185The built-in conversion functionsTO_CHAR( )
TO_NUMBER( )
TO_DATE( )
DECLARE a_number NUMBER; BEGIN a_number := '125'; END;
Jiangping WangWebster University Distributed Database Applications
Implicit Conversation
Jiangping WangWebster University Distributed Database Applications
StringsCHAR(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
Jiangping Wang
PL/SQL subtypes and their equivalentsTable 8-1, page 194
Webster University Distributed Database Applications
String Subtypes
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
Jiangping WangWebster University Distributed Database Applications
Empty Strings are NULLDECLARE
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;
/
Jiangping WangWebster University Distributed Database Applications
String ComparisonsDECLARE
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;
/
Jiangping WangWebster University Distributed Database Applications
String FunctionsASCII, CHR
CHR(64) -- which is ‘@’
INSTRDECLARE company_name VARCHAR2(30) := 'Microsoft Inc.';BEGIN DBMS_OUTPUT.PUT_LINE(INSTR (company_name, 'Inc'));END;
LENGTHLENGTH(‘abcd’) -> 4LENGTH(NULL) -> NULL
SUBSTR, LOWER, UPPER, INITCAPCONCAT
begin dbms_output.put_line('abc' || 'def' || 'ghi'); dbms_output.put_line(concat(concat('abc','def'),'ghi'));end;
Jiangping WangWebster University Distributed Database Applications
NumbersNUMBER
NUMBER(precision, scale)NUMBER(9,2)NUMBER(9,11)NUMBER(9,-11)Rounding of values (page 234)
PLS_INTEGERUses native machine arithmetic
BINARY_INTEGEREquivalent to PLS_INTEGER (since 10g)Uses platform independent library code (before 10g)
Numeric subtypes (page 246)
Jiangping Wang
Numeric Subtypes
Webster University Distributed Database Applications
Jiangping WangWebster University Distributed Database Applications
Numeric FunctionsTO_NUMBER
begin dbms_output.put_line(to_number('12345.67'));end;
TO_CHARDECLARE b VARCHAR2(30);BEGIN b := TO_CHAR(123456789.01,'L999G999G999D99'); DBMS_OUTPUT.PUT_LINE(b);END;
ABS, CEIL, FLOOR, POWER, SQRT
Jiangping WangWebster University Distributed Database Applications
Date and TimeDATETIMESTAMP TIMESTAMP WITH TIME ZONE TIMESTAMP WITH LOCAL TIME ZONE
Jiangping Wang
Effect of different datetime datatypesFigure 10-1, page 269
Date and Time
Webster University Distributed Database Applications
Jiangping Wang
Comparison of functions that return current data and time
Table 10-1, page 272
Webster University Distributed Database Applications
Date and Time
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
Jiangping WangWebster University Distributed Database Applications
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()
Jiangping Wang
Date/Time FormatTo display, the Date value is converted from the internal format to a printable stringOracle's default format for Date is
DD-MON-YY
To covert explicitlyTO_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 WangWebster University Distributed Database Applications
TIMESTAMPTIMESTAMP datatypes
TIMESTAMP
DECLAREtoday_date TIMESTAMP := SYSDATE;
BEGINdbms_output.put_line(TO_CHAR(today_date));
END;
DECLAREthe_day date := to_date('22-MAR-2006');
BEGINdbms_output.put_line(the_day);
END;
Jiangping WangWebster University Distributed Database Applications
Date/Time FunctionsADD_MONTHS functionBEGIN
dbms_output.put_line(add_months(sysdate, 3));dbms_output.put_line(add_months(sysdate, -3));
END;LAST_DAY functionDECLARE
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 functionDECLARE
the_day date := to_date('28-FEB-2010');BEGIN
dbms_output.put_line(months_between(sysdate, the_day));END;
Jiangping WangWebster University Distributed Database Applications
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
Jiangping WangWebster University Distributed Database Applications
Declaring RecordsTable-based record
one_book books%rowtype;l_employee employee%rowtype;
Cursor-based recordcursor 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;
Jiangping WangWebster University Distributed Database Applications
Declaring Records
Programmer-defined recordTYPE book_info_rt IS RECORD (
author books.author%TYPE,
category VARCHAR2(100),
total_page_count POSITIVE);
steven_as_author book_info_rt; -- not %ROWTYPE
Jiangping WangWebster University Distributed Database Applications
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;
Jiangping WangWebster University Distributed Database Applications
Working with RecordsDECLARE
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;
Jiangping WangWebster University Distributed Database Applications
Record-Level OperationsCopy contents of one record to anotherAssign a value of NULL to a record with a simple assignmentDefine and pass record as an argument in a parameter listRETURN a record back through the interface of a functionInsert into a database table with record
Since Oracle9i Database Release 2
Jiangping WangWebster University Distributed Database Applications
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 recordsCompare each field individually
Jiangping WangWebster University Distributed Database Applications
Field-Level OperationsDECLARE 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;
Jiangping WangWebster University Distributed Database Applications
Comparing Records
To test for record equality, each field has to be compared individuallyCompare for NULL(first_book.favorite_author = second_book.favorite_author
OR
(first_book.favorite_author IS NULL AND second_book.favorite_author IS NULL)
Jiangping WangWebster University Distributed Database Applications
CollectionsA collection is a list of itemsOne dimensioned arrayDefine a particular structure using the TYPE statement – datatypeDeclare the actual collection based on the table typeTypes of collections
Associative arraysNested tablesVARRAYs
Jiangping Wang
CollectionsAssociative arrays
Single-dimensional, unbounded, sparse collections of homogeneous elementsPL/SQL only
Nested tablesSingle-dimensional, unbounded collections of homogeneous elementsCan be sparse
VARRAYsSingle-dimensional collections of homogeneous elementsalways bounded and never sparse
Webster University Distributed Database Applications
Jiangping WangWebster University Distributed Database Applications
Collectionsdeclare
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;
beginbirthdays.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;
Jiangping WangWebster University Distributed Database Applications
CollectionsDECLARE
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;
Jiangping WangWebster University Distributed Database Applications
Miscellaneous Datatypes
Boolean datatypeROWID and UROWIDLOB datatypeXMLType datatype
Jiangping WangWebster University Distributed Database Applications
Boolean DatatypeDECLARE 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
Jiangping WangWebster University Distributed Database Applications
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;/
Jiangping WangWebster University Distributed Database Applications
LOB Datatype
BFILEFile locator point to an operating system file outside the database
BLOB, CLOB, NCLOBLOB locator point to a large object stored inside the database
Jiangping WangWebster University Distributed Database Applications
XMLType Datatype
Use XMLType to define database columns and PL/SQL variablesMethods defined on XMLType
Instantiate new XMLType valuesExtract portions of an XML documentManipulate the contents of an XML document
Jiangping WangWebster University Distributed Database Applications
XMLType TypeCREATE 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;
Jiangping WangWebster University Distributed Database Applications
HomeworkCreate 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