Tài liệu Teach Yourself PL/SQL in 21 Days- P8 pptx

50 360 0
Tài liệu Teach Yourself PL/SQL in 21 Days- P8 pptx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Writing Database Triggers 327 11 49: ‘Employees are limited to a max of two departments.’); 50: END IF; 51: END LOOP; 52: END; 53: / 54: Trigger created. Notice in line 1 that the previous trigger is dropped. Be sure to do this. The table-level before trigger in lines 3–9 is fired at the beginning of an INSERT or UPDATE statement. It calls a package procedure that initializes the list counter. The row- level trigger, named only_two_departments_2 (defined in lines 11–19), is fired for each row added or changed. This trigger adds the primary key of each record to the list main- tained in the package-level PL/SQL table. The third trigger, defined in lines 21–52, is the one that does the actual validation work. It is fired after the INSERT or UPDATE statement is complete. It loops through each new or changed record and checks to be sure that each employee in question has a maximum of two department assignments. Now that you have created these triggers and the emp_dept_procs package, you can exe- cute the SQL statements shown in Listing 11.22 in order to demonstrate that it works. L ISTING 11.22 Testing the Triggers and Package That Enforce the Two-Department Rule 1: INSERT INTO employee 2: (emp_id,emp_name) VALUES (403,’Freddie Fisher’); 3: 1 row created. 4: INSERT INTO employee 5: (emp_id,emp_name) VALUES (404,’Charlie Tuna’); 6: 1 row created. 7: INSERT INTO department 8: (dept_id, dept_name) VALUES (404,’Scale Processing’); 9: 1 row created. 10: INSERT INTO department 11: (dept_id, dept_name) VALUES (405,’Gutting’); 12: 1 row created. 13: INSERT INTO department 14: (dept_id, dept_name) VALUES (406,’Unloading’); 15: 1 row created. 16: INSERT INTO emp_dept 17: (emp_id, dept_id) VALUES (403,404); 18: 1 row created. 19: INSERT INTO emp_dept 20: (emp_id, dept_id) VALUES (403,405); 21: 1 row created. 22: INSERT INTO emp_dept A NALYSIS continues I NPUT / O UTPUT 15 7982 ch11 11/30/99 1:12 PM Page 327 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 23: (emp_id, dept_id) VALUES (404,405); 24: 1 row created. 25: INSERT INTO emp_dept 26: (emp_id, dept_id) VALUES (404,406); 27: 1 row created. 28: INSERT INTO emp_dept 29: (emp_id, dept_id) VALUES (403,406); 30: INSERT INTO emp_dept 31: * 32: ERROR at line 1: 33: ORA-20000: Employees are limited to a max of two departments. 34: ORA-06512: at “MY_READER.ONLY_TWO_DEPARTMENTS_3”, line 21 35: ORA-04088: error during execution of trigger ➥’MY_READER.ONLY_TWO_DEPARTMENTS_3’ 36: UPDATE emp_dept 37: SET dept_id = 406 38: WHERE emp_id = 403 AND dept_id = 405; 39: 1 row updated. 40: UPDATE emp_dept 41: SET emp_id = 403 42: WHERE emp_id = 404 43: AND dept_id = 405; 44: update emp_dept 45: * 46: ERROR at line 1: 47: ORA-20000: Employees are limited to a max of two departments. 48: ORA-06512: at “MY_READER.ONLY_TWO_DEPARTMENTS_3”, line 21 49: ORA-04088: error during execution of trigger ‘MY_READER.ONLY_TWO_DEPARTMENTS_3’ The first five inserts (lines 1–15) put some sample employees and departments in place for testing purposes. The next four inserts (lines 16–27) assign each of the two employees just inserted to two departments. The tenth insert (lines 28–29) attempts to assign employee number 403 to a third department. This violates the two-department rule, causing the insert to fail (lines 30–35). There are two UPDATE statements. The first update (lines 36–38) is allowed because it only changes a department assignment for employee number 403. That employee still has exactly two departments. The second update (lines 40–43) fails because it is changing the emp_id field in a record from 404 to 403, resulting in 403 having more than two department assignments. 328 Day 11 L ISTING 11.22 continued A NALYSIS 15 7982 ch11 11/30/99 1:12 PM Page 328 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Writing Database Triggers 329 11 Summary This chapter has been complex, but it gave you the chance to see and experiment with triggers implementing several different types of functionality. To reiterate, some possible uses for triggers are to enforce business rules, generate column values (Listing 11.3), enhance security, and maintain a historical record (Listing 11.6). These are just the tip of the iceberg. The possibilities are limited only by your creativity and imagination. You have also learned about the mutating table error, the bane of many trigger writers, and should now have a good understanding of how to work around it. Q&A Q If I am using a trigger to enforce a business rule or a referential integrity rule, does this affect the records that predate creation of the trigger? A No, it doesn’t, and that’s a good point to keep in mind. When you create a declara- tive constraint, you are really making a statement about the data that must always be true. You cannot create a constraint if data is present that violates that constraint. Triggers, on the other hand, affect only records that have been inserted, updated, or deleted after the trigger was created. For example, creating the triggers limiting an employee to only two department assignments will do nothing about preexisting cases where an employee has more than two assignments. Q The inserts in Listing 11.18 (lines 16–27) did not generate a mutating table error message, yet they did query the table. Why is this? A Single-row inserts are an exception to the rule about querying the underlying table. However, if the insert is one that could possibly create more than one row, for example an INSERT INTO emp_dept SELECT . ,the rule about not querying the mutating table still applies. The solution shown in Listings 11.20 and 11.21 will work when triggers only need to query the mutating table. The problem gets more complex if you need to update those rows. Updating records in the mutating table from a trigger will fire off the very same set of triggers that will also try to use the very same package-level PL/SQL table to build a list of affected records, thus clobbering the data needed to validate the initial update. Caution 15 7982 ch11 11/30/99 1:12 PM Page 329 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Q What’s the difference between a statement-level trigger and a row-level trigger? A A statement-level trigger is executed only once, either before or after the triggering SQL statement executes. It cannot refer to any values in the rows affected by the statement. A row-level trigger fires once for each row affected by the triggering SQL statement and can reference the values for each of the rows. QWhy should I generally validate business rules in a before trigger rather than an after trigger? A It’s potentially more efficient because you can prevent Oracle from doing the work involved in inserting, updating, or deleting a record. By validating in an after trig- ger, you are allowing Oracle to first update the table in question, update any index- es that might be affected by the change, and possibly fire off other triggers. Q The triggers in Listing 11.3 maintain employee counts for each department as records are inserted into, updated in, and deleted from the emp_dept table. What happens, however, if a department record is deleted and then reinsert- ed? Won’t the employee count be reset to zero in that case, making it incorrect? A Yes, this is absolutely true. Typically, in a production database, you would also have referential integrity constraints defined to prevent deletion of department records referenced by other tables. Q Can I define DDL triggers on a specific schema object such as a table? A No, you cannot. Oracle may have plans to change this. The syntax certainly leaves that possibility open. For now though, you may only define DDL triggers at the schema level. Workshop Use the following sections to test your comprehension of this chapter and put what you’ve learned into practice. You’ll find the answers to the quiz and exercises in Appendix A, “Answers.” Quiz 1. Which data manipulation statements can support triggers? 2. What are the four basic parts of a trigger? 3. In a trigger, what are the correlation names :OLD and :NEW used for? 330 Day 11 15 7982 ch11 11/30/99 1:12 PM Page 330 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Writing Database Triggers 331 11 4. What is the name of the system view that can be used to retrieve trigger definitions? 5. What is a mutating table? 6. Name some possible uses for triggers. Exercises 1. Write a set of triggers to maintain the emp_name and dept_name fields redundantly in the emp_dept table so that you do not have to join with the employee and depart- ment tables just to get a simple department listing. 2. Write the SQL statements necessary to populate the emp_name and dept_name fields for any existing emp_dept records. 15 7982 ch11 11/30/99 1:12 PM Page 331 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 15 7982 ch11 11/30/99 1:12 PM Page 332 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. D AY 12 W EEK 2 Using Oracle8i Objects for Object-Oriented Programming by Jonathan Gennick PL/SQL and Oracle contain a limited amount of support for object-oriented programming. Object-oriented features were first introduced in Oracle release 8.0, and make it possible to define object classes, instantiate, or to construct, objects, and save those objects in the database. Although it’s not yet clear whether PL/SQL’s object-oriented features are catching on with developers, you should certainly be aware of them. The potential benefits to you are increased opportunities for abstraction and for writing reusable code. Today you will learn: •How to define an Oracle object type. •How to create an object table, and how to use PL/SQL to store objects in that table. 16 7982 ch12 11/30/99 1:11 PM Page 333 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. •How to create an object column in a regular table, and then access the data in that column from PL/SQL. •How to write the ORDER and MAP methods used when comparing objects. A Brief Primer on Object-Oriented Programming Let’s begin by reviewing the basics of object-oriented programming (OOP). There is really no magic to OOP: It’s simply a way of organizing code and data within your pro- grams, one that you can use to model your code to more closely match the real world. There are three pillars of good object-oriented design: • Encapsulation •Inheritance • Polymorphism Each of these is described in more detail in the following sections, using as examples some real-world objects that you interact with every day. Encapsulation The term encapsulation refers to the fact that each object takes care of itself. A well-designed object has a clear and well-defined interface that is used to manip- ulate the object. All the program code necessary to perform any function on the object is contained within the object definition itself. Thus an object is completely self-contained and can be dropped in anywhere you need it. A classic, and often used, real-world example of objects is audio/video components. Say you are setting up a home theater. You drive to the nearest appliance superstore and pick out whatever objects interest you—a big-screen TV, an FM tuner, an amplifier, and some speakers. All these components have well-defined interfaces, and each contains the inter- nal electronics and software that are necessary to make them work. The FM tuner tunes in radio stations, regardless of whether you plug it in to the amplifier. The TV does not need any circuitry that might be present in the speakers. After integrating all these com- ponents, you might decide that you also want a subwoofer. Adding one is simple. You don’t have to rebuild your stereo system—you just run back to the store, buy the desired component, come home, and plug it in. It sounds pretty easy, but there are some gotchas. In real life, interfaces are not always compatible, and sometimes components have overlapping functionality. That amplifier, 334 Day 12 N EW T ERM 16 7982 ch12 11/30/99 1:11 PM Page 334 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Using Oracle8i Objects for Object-Oriented Programming 335 12 for example, might also have a built-in tuner, and how often have you had to buy an adapter to mate two incompatible connectors? Often it’s easier to work with components that have all been built by the same manufacturer and that have been designed to work together. The same is true in OOP. Inheritance Inheritance refers to the fact that as you design new objects, you often build on objects that have been created previously. In other words, you can create new objects that inherit the functionality of previously created objects. When you do this, you might choose to modify some of the inherited functionality, or you might choose to add new functionality. The telephone is a good example of this. Originally it was a very sim- ple device. You picked up the phone, listened for a dial tone, and dialed a number by using a rotary dial. When pushbutton phones came out, the original functionality was inherited, except for the dialing interface, which was replaced by buttons. Cordless phones inherited this functionality, added a radio to the implementation, and added an on/off switch to the handset interface so that the handset did not need to be returned to the cradle after each call. One big advantage of inheritance in the OOP world, which is not present in the physical world, is that you can change the definition of a software object, and the change will propagate through all objects of that type, all objects inherited from those objects, and so forth. Imagine changing the definition of a telephone to include pushbutton dialing, and as a result having all the rotary phones in the world suddenly transform themselves into pushbutton phones. Of course that can’t be done, but the software equivalent of it can. Polymorphism Polymorphism enables different objects to have methods of the same name that accomplish similar tasks but in different ways. Think back to the home entertain- ment system example for a moment. Each of the components—the TV, the FM tuner, the amplifier, and so forth—has an on button. Many components also have associated remotes, each also with an on button. Each of these buttons can invoke different process- es inside each piece of equipment. A TV remote, for example, has to send an infrared beam of light to the TV set when the on button is pushed. Despite the fact that each on button invokes a different sequence of events, each button is still labeled on. It would be inconvenient if this were not the case. Consistent naming frees your mind from having to remember specifically for each device how to turn it on. You quickly become conditioned to pushing the on button, or flipping a switch to on, no matter what device you are using. N EW T ERM N EW T ERM 16 7982 ch12 11/30/99 1:11 PM Page 335 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Polymorphism similarly enables your software objects to use method names that are con- sistent with the function being performed, even though the way in which that function is implemented can differ from object to object. Classes, Objects, Attributes, and Methods The term class refers to the definition for an object. Like a blueprint for a house, it tells you everything you need to build an object, and it tells you what that object will look like when it is built. An employee class, for example, might be created to contain all attributes of an employee. Examples of employee attributes would be pay rate, name, and address. Many objects can be built from a class, just as one set of blueprints can be used to build numerous houses. If you were writing code to process employee records, you would use the employee class to instantiate,or construct, an employee object for each employee record. Objects consist of attributes and methods. An attribute can be anything you need to know about an object. Name, phone number, Social Security number, pay rate, and pay type are all examples of attributes for an employee object. Attributes are imple- mented as variable declarations made within the object class definition. Methods are the functions and procedures used to perform functions related to the object. Like attributes, methods are implemented as functions and procedures in the object class definition. Anything you want to do to an object should be implemented as a method. If you want to compare two objects, you should implement a compare method. If you want to copy an object, you should implement a copy method. An employee object class, for example, might contain a method to calculate an employee’s yearly bonus based on pay type, longevity with the firm, and so on. Advantages of OOP Over Traditional Methods Objects offer the opportunity for increased reliability because of their well-defined inter- faces. Reuse is made easier because all necessary code and data are part of the object definition; thus object classes can easily be added to programs as new functionality is required. Because you can model real-world business objects, as well as encapsulate and hide the details behind an object’s functionality, you can program at a higher level of abstraction, minimizing the amount of detail you need to remember, which makes your job as a developer much easier. 336 Day 12 N EW T ERM N EW T ERM N EW T ERM 16 7982 ch12 11/30/99 1:11 PM Page 336 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... shown in Listing 12.8 in order to insert a few building objects These will be used in later examples that show how to update object tables and how to link objects in the database INPUT/ OUTPUT LISTING 12.8 Inserting Some building Objects 1: INSERT INTO buildings 2: values (building(‘Victor Building’, 3: address(‘203 Washington Square’,’ ‘,’Lansing’, 4: ‘MI’,’48823’,’ ‘), 5: 597)); 1 row created 12 1: INSERT... NewMgr IN INTEGER), 7: ORDER MEMBER FUNCTION Compare (SELF IN building, 8: OtherBuilding IN building) 9: RETURN INTEGER 10: ); 11: / 12: CREATE OR REPLACE TYPE BODY building AS 13: MEMBER PROCEDURE ChangeMgr(SELF IN OUT building, 14: NewMgr IN INTEGER) IS 15: BEGIN 16: SELF.BldgMgr := NewMgr; continues 362 Day 12 LISTING 12.16 continued 17: END; 18: 19: ORDER MEMBER FUNCTION Compare (SELF IN building,... building table 2: DECLARE 3: this_building building; 4: 5: CURSOR all_buildings IS 6: SELECT value (b) AS bldg 7: FROM buildings b continues 12 354 Day 12 LISTING 12.10 continued 8: ORDER BY b.BldgName; 9: 10: BEGIN 11: FOR one_building IN all_buildings LOOP 12: Grab a copy of the building object 13: this_building := one_building.bldg; 14: dbms_output.put_line(this_building.BldgName || ‘ is located in. .. ChangeMgr(NewMgr IN INTEGER) IS 15: BEGIN 16: BldgMgr := NewMgr; 17: END; 18: 19: ORDER MEMBER FUNCTION Compare (OtherBuilding IN building) 20: RETURN INTEGER IS 21: BldgName1 VARCHAR2(40); 22: BldgName2 building.BldgName%TYPE; 23: BEGIN 24: Grab the two building names for comparison 25: Make sure that we don’t get messed up by leading/trailing 12 continues 350 Day 12 LISTING 12.7 continued 26: spaces... notation in use DECLARE this_building building; BEGIN Retrieve a building object so we can print the attribute values SELECT value(b) INTO this_building FROM buildings b WHERE BldgName = ‘East Storage Shed’; COMMIT; dbms_output.put_line(this_building.BldgName || ‘ ‘ || this_building.BldgAddress.city || ‘ ‘ || this_building.BldgAddress.state_abbr); END; / OUTPUT East Storage Shed Lansing MI PL/SQL procedure... ‘5173363366’) Using Oracle8i Objects for Object-Oriented Programming 347 ANALYSIS Lines 1–4 show how a constructor method can be referenced from within a SQL statement In fact, the statement in question was executed from within SQL*Plus, although it could have been inside a PL/SQL block Lines 12-22 show a PL/SQL block that first instantiates an address object, and then inserts that object into the employee... record The emp_home_address variable is defined in line 13 as being of type address Then in line 15 of the third segment, the address constructor is used to instantiate a new address object, which is assigned to the emp_home_address variable Finally, in lines 17–19, an INSERT statement is executed, saving the employee record The emp_home_address variable is included in the values list and is stored as a... this_building.BldgAddress.city 16: || ‘ ‘ || this_building.BldgAddress.state_abbr); 17: END LOOP; 18: 19: COMMIT; 20: END; 21: / OUTPUT East Storage Shed is located in Lansing MI Headquarters Building is located in Detroit MI Victor Building is located in Lansing MI PL/SQL procedure successfully completed In this example, a cursor is declared (lines 5–8) based on a SQL statement that selects building objects... exists, and because in a Using Oracle8i Objects for Object-Oriented Programming 343 real-life situation, changing an address might involve more than just setting a few attributes Instantiating and Using Objects After you have defined an object type, you probably want to do something with it To use an object from within PL/SQL, you need to follow these steps: 1 Declare one or more variables in which the datatype... EmpNumIn IN employee.emp_id%TYPE, BldgNameIn IN buildings.BldgName%TYPE ) AS BEGIN UPDATE employee SET emp_bldg = (SELECT REF(b) FROM buildings B WHERE BldgName = BldgNameIn) WHERE emp_id = EmpNumIn; Raise an error if either the employee number or building name is invalid IF SQL%NOTFOUND THEN RAISE_application_error(-20000,’Employee ‘ || EmpNumIn || ‘ could not be assigned to building ‘ || BldgNameIn); . prevent Oracle from doing the work involved in inserting, updating, or deleting a record. By validating in an after trig- ger, you are allowing Oracle to first. primary key of each record to the list main- tained in the package-level PL/SQL table. The third trigger, defined in lines 21 52, is the one that does the actual

Ngày đăng: 15/12/2013, 05:15

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan