Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 573 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
573
Dung lượng
2,69 MB
Nội dung
Chapter One An Introduction to Relational Database Tables 1.1 BEFORE RELATIONAL TABLES 1.2 SQL 1.2.1 ANSI Standard 1.2.2 SQL Database 1.2.3 SQL Implementation 1.2.4 SQL*Plus 1.3 TABLES 1.3.1 Data Model View 1.3.2 Create Table Script 1.3.3 Describing the Table 1.3.4 Table Data 1.4 SQL STATEMENTS 1.4.1 Data Definition Language (DDL) 1.4.2 Data Manipulation Language (DML) 1.4.3 Transaction Control 1.4.4 Session Control 1.4.5 System Control 1.5 TABLE COLUMN DATATYPES 1.5.1 Character 1.5.2 Number 1.5.3 DATE Types 1.5.4 Large Objects 1.5.5 XML Type 1.5.6 LONG and RAW Types 1.5.7 ROWID Type 1.6 BEHIND TABLES 1.6.1 Application Tablespaces 1.6.2 Data Dictionary 1.1 Before Relational Tables In 1969, Apollo astronauts Neil Armstrong and Buzz Aldrin walked on the moon That same year Dr Edgar Frank Codd, Ph.D., developed the theory for relational database systems Shortly after this development, Codd published "A Relational Model of Data for Large Shared Data Banks" in the Association of Computing Machinery (ACM) journal, Communications of the ACM Codd's model became the foundation for a prototype; a relational database project within IBM called System/R Studies were performed at the IBM San Jose Research Center (now the Almaden Research Center) and by 1974 IBM had a running prototype relational database system This system was based on multitable queries and multiuser access The method for accessing data in System/R was called Structured English Query Language (SEQUEL) Following its research and development, IBM released System/R as a prototype It was used by the MIT Sloan School of Management and commercial organizations within the manufacturing and inventory sectors The project demonstrated that Codd's theories could be applied and implemented in the real world, but ended in 1979 The success of System/R did not receive quite the same attention the world gave the Apollo astronauts on July 20, 1969; but, System/R's success created a new paradigm in the world of information technologya paradigm that dominates the information age to this day Codd believed that programmers should be able to control the exact data used to join and construct queries from multiple independent tables This was not the case with existing hierarchical and network databases For these other technologies, an application programmer would code an algorithm to navigate through the database by accessing data records based on the predefined navigation paths As software requirements changed, programmers frequently needed database modifications to these paths and new navigations paths needed to be defined The software development process was slow and impaired with frequent meetings on data access Codd's model had a broad impact on the software development process System/R was implemented by a group of highly talented and educated software engineers They demonstrated that large information systems could be built on Codd's theory of multiindependent tables and a structured query language This was the birth of SEQUEL Throughout the System/R project, engineers openly published their work in technical journals and at international conferences The policy of open publication is considered to have been a factor in the success of System/Rleading to the creation of many relational databases such as DB2 and Oracle IBM passed control of the System/R structured query language to the American National Standards Institute (ANSI), a private nonprofit organization that administers U.S voluntary technologies Because of trademark laws, the language was renamed from SEQUEL to SQL for "Structured Query Language." Today SQL is an ANSI standard and an International Standards Organization (ISO) standard In 1977, a group of engineers who had been following the System/R project, primarily through publications, recognized its potential and formed a company This company, Software Development Laboratories, was later named Relational Software This new company developed and marketed the first commercial version of a relational database management system, which was based on the ANSI SQL Standard They named their product Oracle When project System/R ended in 1979, many information systems relied on either hierarchical or network database architecture In the 1980s, many development projects moved toward relational technology Today, the majority of new information systems are relational; however, hierarchical and network database products have still maintained a market presence IMS/DB is the flagship hierarchical database of IBM Rockwell International and IBM developed IMS in 1969 to manage data for the National Aeronautics and Space Administration's (NASA's) Apollo program IMS/DB continues today with a solid international presence It is industry-wide and serves an estimated 200 million end users The IMS/DB database served the Apollo program including Apollo 11, which sent Armstrong, Aldrin, and pilot Mike Collins to the moon Computer Associates' network database product is CA-IDMS, a widely used database serving 2,000 sites around the world The product has changed in name and ownership but continues to support large corporate data systems that run on IBM OS/390 platforms IDMS has an interesting history John J Cullinane founded Cullinet Software, Inc in 1968 He bought the rights to IDMS, a CODASYL database, from B.F Goodrich CODASYL, an acronym for Conference on Data System Languages, was established in 1960 by the Department of Defense for the purpose of standardizing languages and software applications Cullinet was the first software company to be listed on the New York Stock Exchange Computer Associates purchased Cullinet in September of 1989 and renamed the product CA-IDMS Although CA-IDMS is based on database network architecture, the product includes an ANSI-compliant SQL Option This option allows applications to access IDMS data using SQL A set of comprehensive tools is available that includes agents for enterprise monitoring, parallel transaction processing using IBM Parallel Sysplex Cluster Technology, JDBC support for Java, and many other eBusiness technologies The majority of IDMS applications are written in COBOL Oracle, predominately known for the Relational Enterprise Server, owns two additional database products: (a) a network database product called DBMS, which is a CODASYL database, and (b) a relational database product called Rdb Both Rdb and DBMS were purchased from Digital Equipment Corporation (DEC) prior to the acquisition of DEC by Compaq Oracle acquired DBMS when it purchased the Rdb product family from DEC Ken Olsen, an MIT graduate, his brother Stan, and Harlan Anderson founded DEC In addition to hardware architectures such as the PDP-11, VAX, and Alpha, DEC developed Rdb, a relational database, and also DBMS, a network database The network database was renamed from VAX/DBMS to DEC DBMS when version V5.0 was released on the Alpha AXP platform Oracle's CODASYL DBMS is a multi-user network database that, like Rdb, is optimized for the Compaq OpenVMS operating system on either an Alpha or VAX architecture platform DBMS is highly suited for manufacturing systems and shop floor systems that require stable environments where database information is fairly static Consillium Corporation's WorkStream is the most widely installed Manufacturing Execution System (MES) in the semiconductor and electronics industries WorkStream has a long history of running on VAX/DBMS and today runs primarily on VAX and Alpha servers using Oracle CODASYL DBMS Rdb7 was Oracle's first release of Rdb that was conceived and engineered as an Oracle product Oracle's Rdb7 is an enterprise relational database optimized for digital platforms; that is, the Hewlett-Packard Corporation's OpenVMS operating system and Compaq Digital UNIX When Compaq acquired DEC it replaced the DEC version of UNIX, called Ultrix, with the product name DIGITAL UNIXan operating system based on a 64-bit architecture that runs on Alpha AXP platforms In summary, the database market is clearly dominated by relational technology; however, hierarchical and network databases continue to meet the needs of enterprise network computing environments IBM IMS/DB is a dominant hierarchical database that can service high-transaction rates and has a large install base Two network databasesCA-IDMS, licensed by Computer Associates, and DBMS, licensed by Oracle,play critical roles in support of high-transaction enterprise-wide systems In addition to the Oracle Enterprise Server, Oracle Corporation also owns Rdb7, a relational database, and DBMS, a network databaseboth products are optimized for Compaq platforms, including Alpha AXP Today the Oracle Database Server addresses the needs of small and large businesses that require information processing for online transaction processing (OLTP) systems, decision support systems (DSS), plus the eBusiness solutions These types of applications can operate on small, stand-alone servers, or on distributed, high-availability architectures 1.2 SQL SQL means something very specific, whereas the term database has broad meaning and interpretation in everyday conversation This section elaborates on the SQL language as a standard Topics include SQL implementation, embedded SQL, Direct SQL, and SQL*Plus as an implementation of Direct SQL 1.2.1 ANSI Standard SQL is a language currently defined in an ANSI standard (the previous section discussed the history of SQL as it passed from IBM to ANSI) If you are writing an Oracle application that uses SQL, then you are coding SQL statements whose syntax complies with ANSI-X3.135-1999, "Database Language SQL." This ANSI standard is available to the public through the ANSI Web store You can visit the site, http://webstore.ansi.org/ansidocstore/, which has a search form field Using the search field, you can find SQL standards with a search on "ANSI X3.135." You can obtain copies of this document in PDF format; the cost, as of this writing, is $18 and it contains about 600 pages The standard, as with most standards, is defined using the Backus Naur Form syntaxillustrated next The following extract, from ANSI-X3.135-1999, "Database Language SQL," is shown here to illustrate the preciseness with which the standard defines the syntax of a CREATE TABLE statement ::= CREATE [ { GLOBAL ) LOCAL } TEMPORARY ] TABLE [ ON COMMIT { DELETE I PRESERVE } ROWS ] ::= [ { } ] ::= | So, if you are a database vendor and you sell a SQL database product, then you are telling your customers that your database product is capable of parsing and executing ANSI SQL statements, such as the aforementioned CREATE TABLE statement There is always an advantage to working with a standard It means that your knowledge is transferable An understanding of SQL means that your knowledge of relational database technology can transfer between products such as Oracle and SQL Server Even within a standard there are differences SQL is no exception SQL differs across vendors for two reasons First, there are "implementation defined" features in the standard; that is, for some SQL features, the specific nature of how a feature is implemented is "implementation defined"the standard explicitly states this with the language "implementation defined." This means the vendor has discretion in how the feature is implemented One example is how the vendor implements the catalog or data dictionary The standard cannot impose how a vendor stores database metadata We'll see later in this chapter how Oracle's data dictionary is a set of relational tables from which we can select tremendous amounts of information, such as information describing the tables we create A second reason why there are differences across databases is due to the fact that vendors do enhance their specific SQL engines with additional capabilities that they feel benefit the application developer One example is the DECODE SQL function that you will find in Oracle This is a powerful function that will not necessarily appear in other database products simply because DECODE is not part of the ANSI standard Another example is the database column type CURRENCY that you find in SQL Servernot all database products provide a CURRENCY type These differences are minor compared to the many consistencies across SQL products that are ensured by the ANSI standard In summary, you will find variations in some SQL statements across database enginesthis is really not a big deal For example, if you build your expertise in SQL and you build this knowledge in Oracle, then your knowledge will include an understanding of inner and outer joins If you are ever confronted with the syntax of outer joins from a SQL Server or DB2 application, where this syntax varies, then you can easily make the knowledge transition The key issue is to recognize that there are differences, because you are likely to become exposed to these differences at some point in your career When this happens, just remember that products will have subtle differences even under the umbrella of an ANSI standard 1.2.2 SQL Database The term database is used often in everyday language, but it is important to remember that not all "databases" are created equal Nor can they all be called relational databases The term relational database refers to one based on the SQL standard that is capable of parsing and executing SQL statements We can be very general in how we use the term database, but the term relational database does convey a database that is based on the SQL standardsomething very specific In contrast to relational databases, there are nonrelational 7.1 Sequence of Events You can do the following with an INSERT STATEMENT trigger: You can perform an aggregate computation on the table This can be computed before or after the insert You can use a statement level trigger to process data that is collected by a row trigger This is covered in Section 7.4, "Processing Row Captured Data." You can signal an event This can simply be a print statement It can also be an email or signal to another process using the DBMS_ALERT package Figure 7-1 illustrates the behavior of statement level triggers that can perform "Take Action" functions of "Reject the Transaction" functions The statement level trigger has no knowledge of the before and after values of any changed row For a comparison with row triggers, compare Figure 7-1 with Figure 6-1 Figure 7-1 Statement Level Trigger Figure 7-1 illustrates the statement level behavior It also shows that row level triggers fire between the before-statement and after-statement triggers If three rows are affected by a SQL UPDATE, as is the example in this figure, three row triggers will fire Statement level triggers fire once 7.2 Insert Statement Trigger Syntax The Insert Statement Trigger has the following syntax CREATE OR REPLACE TRIGGER trigger_name [AFTER | BEFORE] INSERT ON table_name DECLARE Local declarations BEGIN Body written PL/SQL END; The key difference in the syntax between the statement and row trigger is the FOR EACH ROW clausethis clause specifically identifies the trigger as row level and is not in the statement level trigger The statement trigger syntax that designates the triggering event is the same as row triggers Refer to Chapter 6, "Row Trigger Syntax," for a thorough discussion on trigger naming conventions and the OF COLUMN_NAME clause The following are valid clauses for statement level triggers, as well as row triggers BEFORE INSERT OR UPDATE OR DELETE ON table_name AFTER INSERT OR UPDATE OF column_name OR DELETE ON table_name The following are two key points with regard to trigger options: Table WHEN (Boolean expression) ALL ROW triggers only OF column_name clause Valid for UPDATE ROW and STATEMENT triggers only The syntax for statement level triggers is simpler than row triggers The following features do not exist with statement level triggers: There is no WHEN (Boolean expression) that voids any discussion of OLD.COLUMN_NAME and NEW.COLUMN_NAME expressions References to :NEW.COLUMN_NAME and :OLD.COLUMN_NAME are invalid The combination of row and statement triggers is 12 types of triggers The following summarizes the template for each trigger Trigger Type Triggering Event Create or Replace (example: TEMP table) BEFORE STATEMENT INSERT TRIGGER TEMP BEFORE INSERT ON TEMP BEGIN Body END BEFORE EACH ROW[a] INSERT TRIGGER TEMP BEFORE INSERT ON TEMP FOR EACH ROW BEGIN Body END AFTER EACH ROW[a] INSERT TRIGGER TEMP AFTER INSERT ON TEMP FOR EACH ROW BEGIN Body END AFTER STATEMENT INSERT TRIGGER TEMP AFTER INSERT ON TEMP BEGIN Body END BEFORE STATEMENT UPDATE[b] TRIGGER TEMP BEFORE UPDATE ON TEMP BEGIN Body END BEFORE EACH ROW[a] UPDATE[b] TRIGGER TEMP BEFORE UPDATE ON TEMP FOR EACH ROW BEGIN Body END AFTER EACH ROW[a] UPDATE[b] TRIGGER TEMP AFTER UPDATE ON TEMP FOR EACH ROW BEGIN Body END AFTER STATEMENT UPDATE[b] TRIGGER TEMP AFTER UPDATE ON TEMP BEGIN Body END BEFORE STATEMENT DELETE TRIGGER TEMP BEFORE DELETE ON TEMP BEGIN Body END BEFORE EACH ROW[a] DELETE TRIGGER TEMP BEFORE DELETE ON TEMP FOR EACH ROW BEGIN Body END AFTER EACH ROW[a] TRIGGER TEMP AFTER DELETE ON TEMP FOR EACH ROW BEGIN Body DELETE END AFTER STATEMENT DELETE TRIGGER TEMP AFTER DELETE ON TEMP BEGIN Body END [a] WHEN (Boolean expression) is optional with all row triggers [b] OF COLUMN_NAME clause is optional on UPDATE ROW and STATEMENT triggers Although this table illustrates 12 distinct triggers, any trigger type, such as a BEFORE STATEMENT trigger, can combine triggering events such as the following: CREATE OR REPLACE TRIGGER temp_biuds BEFORE INSERT OR UPDATE OR DELETE ON TEMP BEGIN CASE WHEN inserting THEN PL/SQL code here WHEN updating THEN PL/SQL code here WHEN deleting THEN PL/SQL code here END CASE; END; 7.3 Statement Level Aggregation Statement triggers can enforce business rules where the rule is based on a table aggregate Although a row trigger can restrain a salary for a particular row, a statement trigger can constrain the result of SUM(salary) This is essentially a constraint on the entire table This is quite different from constraints discussed so far Initially, simple rules are enforced with a CHECK constraint Chapter 6 illustrates a more complex rule that restricts the salary for any professor in the English department while leaving the CHECK constraint to enforce a salary restriction for non-English professors Consider the following rules A professor cannot be added if the current budget exceeds $55,000 The total budget cannot exceed $60,000 These can be enforced with statement level triggers The first trigger, BEFORE STATEMENT, will reject any transaction that attempts to add a professor when the current budget exceeds $55,000 The AFTER STATEMENT trigger rejects the transaction when the result of adding a professor exceeds the sum of $60,000 The data for the PROFESSORS table in Chapter 4, Section 4.4, "Sample Data," shows the current sum at $50,000 We could add a single professor with a salary of $10,000 This would pass the business rule test However, the BEFORE STATEMENT trigger will reject any additional inserts Secondly, we could insert a salary of $5,000 This would be allowed However, the AFTER STATEMENT trigger will likely reject any sizable insert after that The implementation of these business rules will require the following steps Update the ERRORS package with error numbers Encapsulate the business rule logic in a constraints enforcement package Write the before and after statement trigger The first step is to declare error numbers and message text in the errors package from Chapter 6 This is the central definition for errors raised through the application The ERRORS package is updated to include two error numbers: 20002 and 20003 CREATE OR REPLACE PACKAGE errors IS eng_dept_sal CONSTANT PLS_INTEGER := -20001; app_error_02 CONSTANT PLS_INTEGER := -20002; app_error_03 CONSTANT PLS_INTEGER := -20003; eng_dept_sal_txt CONSTANT VARCHAR2(100) := 'The salary exceeds the ENGL maximum of $10,000.00'; app_error_02_txt CONSTANT VARCHAR2(100) := 'No additions if the budget exceeds $55,000.00'; app_error_03_txt CONSTANT VARCHAR2(100) := 'Budget cannot be over $60,000.00'; END errors; The next step is to encapsulate the business logic in a constraints package Such a package was developed in Chapter We can revive PROFESSORS_CONS The following shows the package spec and body, minus the package procedure code from Chapter 6 The following code implements a single procedure that is used by the BEFORE and AFTER statement trigger There are several styles for coding this One is to make a separate procedure for each trigger With this interface the trigger must pass the arguments that specify the constraint limit, error code, and text CREATE OR REPLACE PACKAGE professors_cons IS PROCEDURE constrain_budget (limit NUMBER,err_code PLS_INTEGER,err_text VARCHAR2); END professors_cons; CREATE OR REPLACE PACKAGE BODY professors_cons IS PROCEDURE constrain_budget (limit NUMBER,err_code PLS_INTEGER,err_text VARCHAR2) IS budget_sum NUMBER; BEGIN SELECT SUM(salary) INTO budget_sum FROM professors; IF budget_sum > limit THEN RAISE_APPLICATION_ERROR(err_code, err_text); END IF; END constrain_budget; END professors_cons; The BEFORE and AFTER statement triggers are the last and final step As always, the body of the trigger is short and simple Because both INSERT and UPDATE statements can potentially violate the rule, the triggering event is set to INSERT OR UPDATE CREATE OR REPLACE TRIGGER professors_bis BEFORE INSERT OR UPDATE ON professors BEGIN professors_cons.constrain_budget (55000, errors.budget_err_1, errors.budget_err_1_txt); END; CREATE OR REPLACE TRIGGER professors_ais AFTER INSERT OR UPDATE ON professors BEGIN professors_cons.constrain_budget (60000, errors.budget_err_2, errors.budget_err_2_txt); END; If these rules are in place (i.e., the packages and trigger compile) we can insert this next professor: INSERT INTO professors VALUES ('Smith', 'Mathematics', SYSDATE, 10000.00, 'YES','MATH'); However, any further INSERTs will be rejected by the BEFORE statement trigger This is due to the fact that the current SUM(SALARY) exceeds $55,000 We can insert this professor: INSERT INTO professors VALUES ('Smith', 'Mathematics', SYSDATE, 5000.00, 'YES','MATH'); However, any sizable addition to the staff will pass the first validation in the BEFORE statement trigger (the budget is at $55,000), but will be rejected by the second, the AFTER statement trigger This would occur if the salary of this addition caused the SUM(SALARY) to exceed $60,000 7.4 Processing Row Captured Data Row triggers can store :OLD and :NEW column values in a global temporary table The scope of a global temporary table is just that transaction By copying :OLD and :NEW values, the processing of the business rule can be deferred to the statement level trigger Sometimes this is necessary because the business rule is complex and requires queries from tables, including the table being updated The following illustrates the general technique First a global temporary table is needed This table will be used to store data in the row level trigger CREATE global temporary TABLE professors_g (prof_name VARCHAR2(10), specialty VARCHAR2(20), hire_date DATE, salary NUMBER(7,2), tenure VARCHAR2(3), department VARCHAR2(10)) ON COMMIT DELETE ROWS; The next step is to code procedures in the constraints package for this table These procedures will be added to the PROFESSORS_CONS package Showing just the additions for the package specification: CREATE OR REPLACE PACKAGE professors_cons IS PROCEDURE load_temp_table (v_prof_name professors.prof_name%TYPE, v_specialty professors.specialty%TYPE, v_hire_date professors.hire_date%TYPE, v_salary professors.salary%TYPE, v_tenure professors.tenure%TYPE, v_department professors.department%TYPE); PROCEDURE dump_temp_table; END professors_cons; The package body is: CREATE OR REPLACE PACKAGE BODY professors_cons IS PROCEDURE load_temp_table (v_prof_name professors.prof_name%TYPE, v_specialty professors.specialty%TYPE, v_hire_date professors.hire_date%TYPE, v_salary professors.salary%TYPE, v_tenure professors.tenure%TYPE, v_department professors.department%TYPE) IS BEGIN INSERT INTO professors_g VALUES (v_prof_name, v_specialty, v_hire_date, v_salary, v_tenure, v_department); END load_temp_table; PROCEDURE dump_temp_table IS BEGIN FOR rec in (SELECT * FROM professors_g) LOOP dbms_output.put_line( rec.prof_name||' '||rec.specialty||' '|| rec.hire_date||' '||rec.salary||' '|| rec.tenure||' '||rec.department); END LOOP; END dump_temp_table; END professors_cons; The following is a AFTER DELETE ROW trigger When this trigger fires it only inserts row data in the temporary table through the PROFESSORS_CONS package CREATE OR REPLACE TRIGGER professors_adr AFTER DELETE ON professors FOR EACH ROW BEGIN professors_cons.load_temp_table (:old.prof_name, :old.specialty, :old.hire_date, :old.salary, :old.tenure, :old.department); END; The next trigger is an AFTER DELETE STATEMENT trigger that uses the constraints package to print the rows deleted Although this demonstration merely prints the data, in some circumstances this can be useful to a statement level trigger Statement level triggers have no knowledge of the rows affected by the SQL statement They have no knowledge of :OLD and :NEW values The AFTER DELETE statement trigger is: CREATE OR REPLACE TRIGGER professors_ads AFTER DELETE ON professors BEGIN professors_cons.dump_temp_table; END; The DELETE SQL statement is followed by the output from the statement trigger SQL> DELETE FROM professors; Blake Mathematics 08-aug-2003 02:06:27 10000 YES MATH Milton Am Hist 09-aug-2003 02:06:27 10000 YES HIST Wilson English 06-aug-2003 02:06:27 10000 YES ENGL Jones Euro Hist 12-jul-2003 02:06:28 10000 YES HIST Crump Ancient Hist 12-jul-2003 02:06:28 10000 YES HIST 5 rows deleted ... database objects and result in updates to the Oracle data dictionary They create, modify, and delete objects such as a tables, views, stored procedures, database triggers, database links, and dozens of other objects in the database... Oracle acquired DBMS when it purchased the Rdb product family from DEC Ken Olsen, an MIT graduate, his brother Stan, and Harlan Anderson founded DEC In addition to hardware architectures such as the PDP-11, VAX, and Alpha, DEC developed Rdb, a relational database, and also DBMS, a... (MES) in the semiconductor and electronics industries WorkStream has a long history of running on VAX/DBMS and today runs primarily on VAX and Alpha servers using Oracle CODASYL DBMS Rdb7 was Oracle' s first release of Rdb that was conceived and