Matthew P. Johnson, OCL1, CISDD CUNY, F20041 OCL1 Oracle 10g: SQL & PL/SQL Session #9 Matthew P. Johnson CISDD, CUNY Fall, 2004.

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

Manipulating Data Schedule: Timing Topic 60 minutes Lecture
Triggers. Triggers: Motivation Assertions are powerful, but the DBMS often can’t tell when they need to be checked. Attribute- and tuple-based checks.
Triggers The different types of integrity constraints discussed so far provide a declarative mechanism to associate “simple” conditions with a table such.
Creating Triggers.
End of SQL: Triggers, Impedance Mismatch and Transactions February 6 th, 2004.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #21 M.P. Johnson Stern School of Business, NYU Spring, 2008.
1 Table Alteration. 2 Altering Tables Table definition can be altered after its creation Adding columns Changing columns’ definition Dropping columns.
1Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 OCL4 Oracle 10g: SQL & PL/SQL Session #7 Matthew P. Johnson CISDD, CUNY June, 2005.
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5 (cont.)
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #19 M.P. Johnson Stern School of Business, NYU Spring, 2005.
Triggers in SQL’99 CS561.
Triggers.
Triggers. What is a trigger? A trigger defines an action that the database should take when some event occurs in the application. It is triggered by an.
Chapter 5 Data Manipulation and Transaction Control Oracle 10g: SQL
Cs3431 Triggers vs Constraints Section 7.5. cs3431 Triggers (Make DB Active) Trigger: A procedure that starts automatically if specified changes occur.
SQL: Constraints and Triggers Chapter 6 Ullman and Widom Certain properties we’d like our database to hold Modification of the database may break these.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Triggers A Quick Reference and Summary BIT 275. Triggers SQL code permits you to access only one table for an INSERT, UPDATE, or DELETE statement. The.
1 ICS 184: Introduction to Data Management Lecture Note 11: Assertions, Triggers, and Index.
Triggers and Stored Procedures in DB 1. Objectives Learn what triggers and stored procedures are Learn the benefits of using them Learn how DB2 implements.
In Oracle.  A PL/SQL block stored in the database and fired in response to a specified event ◦ DML statements : insert, update, delete ◦ DDL statements.
9 Copyright © 2007, Oracle. All rights reserved. Managing Data and Concurrency.
Oracle 11g DATABASE DEVELOPMENT LAB1. Introduction  Oracle 11g Database:-  Oracle 11g database is designed for some features, which helps to the organizations.
Constraints, Triggers and Views COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, VEHARI.
1 ISYS Triggers. 2 Agenda Triggers Review Correlation identifiers (pseudo records) Restrictions on triggers Trigger usage Mutating tables Enabling.
8 Copyright © 2005, Oracle. All rights reserved. Managing Data.
Fall 2001Database Systems1 Triggers Assertions –Assertions describe rules that should hold for a given database. –An assertion is checked anytime a table.
Advanced SQL: Triggers & Assertions
Creating DDL and Database Event Triggers. 2 home back first prev next last What Will I Learn? Describe events that cause DDL and database event triggers.
What is a Package? A package is an Oracle object, which holds other objects within it. Objects commonly held within a package are procedures, functions,
7 1 Constraints & Triggers Chapter Constraints and triggers? Constraints: Certain properties that the DBMS is required to enforce –E.g. primary.
Objectives Database triggers and syntax
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
Advanced SQL Concepts - Checking of Constraints CIS 4301 Lecture Notes Lecture /6/2006.
Different Constraint Types Type Where Declared When activated Guaranteed to hold? Attribute with attribute on insertion not if CHECK or update subquery.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Transactions, Roles & Privileges Oracle and ANSI Standard SQL Lecture 11.
1 SQL: Structured Query Language Chapter 5 (cont.)  Constraints  Triggers.
Assertions and Triggers in SQL
A Guide to SQL, Eighth Edition Chapter Six Updating Data.
Constraining Attribute Values Constrain invalid values –NOT NULL –gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)) –MovieName CHAR(30) CHECK (MovieName IN (SELECT.
Distributed Database Applications COSC 5050 Week Six.
A procedure is a module performing one or more actions; it does not need to return any values. The syntax for creating a procedure is as follows: CREATE.
A database trigger is a stored PL/SQL program unit associated with a specific database table. ORACLE executes (fires) a database trigger automatically.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
Database Management COP4540, SCS, FIU Database Trigger.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
SQL Triggers, Functions & Stored Procedures Programming Operations.
Murali Mani Constraints. Murali Mani Keys: Primary keys and unique CREATE TABLE Student ( sNum int, sName varchar (20), dept char (2), CONSTRAINT key.
Oracle 11g: SQL Chapter 5 Data Manipulation and Transaction Control.
1 Constraints and Triggers in SQL. 2 Constraints are conditions that must hold on all valid relation instances SQL2 provides a variety of techniques for.
ISYS Triggers.
Creating Database Triggers
C : Database Management Systems Lecture #20
SQL Stored Triggers Presented by: Dr. Samir Tartir
Introduction to Triggers
Introduction to Database Systems, CS420
Agenda Triggers Review Correlation identifiers (pseudo records)
ISYS Triggers.
Advanced SQL: Views & Triggers
Instructor: Mohamed Eltabakh
Introduction to Triggers
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Prof. Arfaoui. COM390 Chapter 9
TRIGGERS.
Presentation transcript:

Matthew P. Johnson, OCL1, CISDD CUNY, F20041 OCL1 Oracle 10g: SQL & PL/SQL Session #9 Matthew P. Johnson CISDD, CUNY Fall, 2004

Matthew P. Johnson, OCL1, CISDD CUNY, F Agenda Triggers Constraints Transactions Oracle’s bulk loader PL/SQL lab Today’s lab

Matthew P. Johnson, OCL1, CISDD CUNY, F What are triggers? PL/SQL programs that run automatically (are “triggered”) when a certain event occurs E.g.: on insert to some table On system start-up On delete from table Big benefit: need not be called explicitly However row in table x is deleted, the trigger gets called

Matthew P. Johnson, OCL1, CISDD CUNY, F Trigger events Trigger code may be “triggered” by many kinds of events: Oracle start-up/shut-down  Triggers may replace initialization scripts Data updates:  Delete: maybe delete related rows  Inserts  Updates: maybe make other rows consistent  Delete: maybe prevent DDL statements  Log creation of all objects, e.g.

Matthew P. Johnson, OCL1, CISDD CUNY, F Triggers Constraints state what must remain true  DBMS decides when to check Triggers are instructions to perform at explicitly specified times Three aspects:  An event (e.g., update to an attribute)  A condition (e.g., a query to check)  An action (the trigger’s effect) (deletion, update, insertion) When the event occurs, DBMS checks the constraint, and if it is satisfied, performs the action

Matthew P. Johnson, OCL1, CISDD CUNY, F DML trigger options The trigger may be:  Statement-level (e.g., a DELETE WHERE statement) or  Row-level (e.g., for each row deleted) The trigger may run  BEFORE  AFTER or  INSTEAD OF the statement It may be triggered by  INSERTs  UPDATEs  DELETEs

Matthew P. Johnson, OCL1, CISDD CUNY, F Trigger form CREATE [OR REPLACE] TRIGGER trigger name {BEFORE | AFTER| {INSERT | DELETE | UPDATE | UPDATE OF column list} ON table name [FOR EACH ROW] [WHEN (...)] [DECLARE... ] BEGIN... executable statements... [EXCEPTION... ] END [trigger name]; CREATE [OR REPLACE] TRIGGER trigger name {BEFORE | AFTER| {INSERT | DELETE | UPDATE | UPDATE OF column list} ON table name [FOR EACH ROW] [WHEN (...)] [DECLARE... ] BEGIN... executable statements... [EXCEPTION... ] END [trigger name];

Matthew P. Johnson, OCL1, CISDD CUNY, F Trigger type examples First run copy_tables.sql 1. statement_vs_row.sql  INSERT INTO to_table SELECT * FROM from_table; 2. before_vs_after.sql  INSERT INTO to_table SELECT * FROM from_table; 3. one_trigger_per_type.sql  INSERT INTO to_table VALUES (1); UPDATE to_table SET col1 = 10; DELETE to_table;

Matthew P. Johnson, OCL1, CISDD CUNY, F DML Trigger e.g. Q: Why is this (maybe) better than client-side validation? CREATE OR REPLACE TRIGGER validate_employee_changes BEFORE INSERT OR UPDATE ON employee FOR EACH ROW BEGIN check_age (:NEW.date_of_birth); check_resume (:NEW.resume); END; CREATE OR REPLACE TRIGGER validate_employee_changes BEFORE INSERT OR UPDATE ON employee FOR EACH ROW BEGIN check_age (:NEW.date_of_birth); check_resume (:NEW.resume); END;

Matthew P. Johnson, OCL1, CISDD CUNY, F Triggers with WHEN NB: WHEN applies only to row-level triggers CREATE OR REPLACE TRIGGER check_raise AFTER UPDATE OF salary, commission ON employee FOR EACH ROW WHEN ((OLD.salary != NEW.salary OR (OLD.salary IS NULL AND NEW.salary IS NULL)) OR (OLD.commission != NEW.commission OR (OLD.commission IS NULL AND NEW.commission IS NULL))) BEGIN... END; CREATE OR REPLACE TRIGGER check_raise AFTER UPDATE OF salary, commission ON employee FOR EACH ROW WHEN ((OLD.salary != NEW.salary OR (OLD.salary IS NULL AND NEW.salary IS NULL)) OR (OLD.commission != NEW.commission OR (OLD.commission IS NULL AND NEW.commission IS NULL))) BEGIN... END;

Matthew P. Johnson, OCL1, CISDD CUNY, F Triggers with WHEN Remember: WHEN applies only to row-levels Parentheses are required Can only call built-in functions in when  Packages like DBMS_OUTPUT are not allowed CREATE OR REPLACE TRIGGER valid_when_clause BEFORE INSERT ON frame FOR EACH ROW WHEN ( TO_CHAR(SYSDATE,'HH24') BETWEEN 9 AND 17 )... CREATE OR REPLACE TRIGGER valid_when_clause BEFORE INSERT ON frame FOR EACH ROW WHEN ( TO_CHAR(SYSDATE,'HH24') BETWEEN 9 AND 17 )...

Matthew P. Johnson, OCL1, CISDD CUNY, F Multiple DML actions DML actions may be ORed together CREATE OR REPLACE TRIGGER three_for_the_price_of_one BEFORE DELETE OR INSERT OR UPDATE ON account_transaction FOR EACH ROW BEGIN IF INSERTING THEN :NEW.created_by := USER; :NEW.created_date := SYSDATE; ELSIF DELETING THEN audit_deletion(USER,SYSDATE); END; CREATE OR REPLACE TRIGGER three_for_the_price_of_one BEFORE DELETE OR INSERT OR UPDATE ON account_transaction FOR EACH ROW BEGIN IF INSERTING THEN :NEW.created_by := USER; :NEW.created_date := SYSDATE; ELSIF DELETING THEN audit_deletion(USER,SYSDATE); END; To find actual action, check:  INSERTING  DELETING  UPDATING

Matthew P. Johnson, OCL1, CISDD CUNY, F More on UPDATING UPDATING may be called for partic. columns CREATE OR REPLACE TRIGGER validate_update BEFORE UPDATE ON account_transaction FOR EACH ROW BEGIN IF UPDATING ('ACCOUNT_NO') THEN errpkg.raise('Account number cannot be updated'); END IF; END; CREATE OR REPLACE TRIGGER validate_update BEFORE UPDATE ON account_transaction FOR EACH ROW BEGIN IF UPDATING ('ACCOUNT_NO') THEN errpkg.raise('Account number cannot be updated'); END IF; END;

Matthew P. Johnson, OCL1, CISDD CUNY, F Extended auditing example Tables: grades, grades_audit Run: grades_tables.sql, grades_audit.sql Cases: hacker changes grades, deletes others UPDATE grades SET grade = 'A+' WHERE student_id = 1 AND class_id = 101; UPDATE grades SET grade = 'A+' WHERE student_id = 1 AND class_id = 101; DELETE grades WHERE student_id = 2 AND class_id = 101; DELETE grades WHERE student_id = 2 AND class_id = 101;

Matthew P. Johnson, OCL1, CISDD CUNY, F Extended auditing example Run: grades_tables.sql, grades_audit2.sql Cases: hacker changes student or class ids UPDATE grades SET student_id = 3 WHERE student_id = 1 AND class_id = 101; UPDATE grades SET student_id = 1 WHERE student_id = 2 AND class_id = 101; UPDATE grades SET student_id = 2 WHERE student_id = 3 AND class_id = 101; UPDATE grades SET student_id = 3 WHERE student_id = 1 AND class_id = 101; UPDATE grades SET student_id = 1 WHERE student_id = 2 AND class_id = 101; UPDATE grades SET student_id = 2 WHERE student_id = 3 AND class_id = 101;

Matthew P. Johnson, OCL1, CISDD CUNY, F DDL Triggers Respond to DDL events  Creating/dropping tables, indices, etc.  ALTER TABLE etc. General form: CREATE [OR REPLACE] TRIGGER trigger name {BEFORE | AFTER| {DDL event} ON {DATABASE | SCHEMA} DECLARE Variable declarations BEGIN... some code... END; CREATE [OR REPLACE] TRIGGER trigger name {BEFORE | AFTER| {DDL event} ON {DATABASE | SCHEMA} DECLARE Variable declarations BEGIN... some code... END;

Matthew P. Johnson, OCL1, CISDD CUNY, F DDL trigger e.g. Town crier examples triggered by creates: uninformed_town_crier.sql informed_town_crier.sql

Matthew P. Johnson, OCL1, CISDD CUNY, F Available DDL events CREATE, ALTER, DROP, GRANT, RENAME, REVOKE, TRUNCATE DDL: any DDL event Q: Does this work?? CREATE OR REPLACE TRIGGER no_create AFTER CREATE ON SCHEMA BEGIN RAISE_APPLICATION_ERROR (-20000, 'ERROR : Objects cannot be created in the production database.'); END; CREATE OR REPLACE TRIGGER no_create AFTER CREATE ON SCHEMA BEGIN RAISE_APPLICATION_ERROR (-20000, 'ERROR : Objects cannot be created in the production database.'); END;

Matthew P. Johnson, OCL1, CISDD CUNY, F DB Event triggers Form similar to DDL triggers: Triggering events: STARTUP, SHUTDOWN, SERVERERROR, LOGON, LOGOFF CREATE [OR REPLACE] TRIGGER trigger name {BEFORE | AFTER} {database event} ON {DATABASE | SCHEMA} DECLARE Variable declarations BEGIN... some code... END; CREATE [OR REPLACE] TRIGGER trigger name {BEFORE | AFTER} {database event} ON {DATABASE | SCHEMA} DECLARE Variable declarations BEGIN... some code... END;

Matthew P. Johnson, OCL1, CISDD CUNY, F DB event restrictions Have BEFORE and AFTER as above, but they don’t always apply:  No BEFORE STARTUP/LOGON/SERVERERROR  No AFTER SHUTDOWN/LOGOFF

Matthew P. Johnson, OCL1, CISDD CUNY, F DB Trigger e.g. Gather stat before shutdown: Log error messages: error_log.sql CREATE OR REPLACE TRIGGER on_shutdown BEFORE SHUTDOWN ON DATABASE BEGIN gather_system_stats; END; CREATE OR REPLACE TRIGGER on_shutdown BEFORE SHUTDOWN ON DATABASE BEGIN gather_system_stats; END;

Matthew P. Johnson, OCL1, CISDD CUNY, F Trigger maintenance Enabling & disabling:  ALTER TRIGGER emp_after_insert DISABLE;  ALTER TRIGGER emp_after_insert ENABLE; Deleting:  DROP TRIGGER emp_after_insert; Viewing:  select trigger_name from user_triggers;  select text from user_source where name='TOWN_CRIER'; Check validity:  select object_name, status from user_objects where object_type='TRIGGER';

Matthew P. Johnson, OCL1, CISDD CUNY, F Triggers – important points Can replace old row (result of event) with new row Action may be performed before or after event Can refer to old row and new row WHEN clauses tests whether to continue Action may be performed either  For each row involved in event  Once per event Oracle does triggers as PL/SQL programs A trigger runs in the same transaction as the event triggering it

Matthew P. Johnson, OCL1, CISDD CUNY, F Elements of Triggers Timing of action execution: before, after or instead of triggering event The action can refer to both the old and new state of the database Update events may specify a particular column or set of columns A condition is specified with an optional WHEN clause The action can be performed either for  once for every tuple or  once for all the tuples that are changed by the database operation

Matthew P. Johnson, OCL1, CISDD CUNY, F Simple trigger example R(id, data, last-modified)  data is a large string  Last-modified is a newly added date field Goal: whenever data is modified, update last- modified date Could modify all scripts/programs that touch this table  Bad idea Better: user a trigger CREATE TRIGGER UpdateDateTrigger BEFORE UPDATE OF data ON R REFERENCING NEW ROW AS NewTuple FOR EACH STATEMENT BEGIN NewTuple.last-modified = sysdate; END; CREATE TRIGGER UpdateDateTrigger BEFORE UPDATE OF data ON R REFERENCING NEW ROW AS NewTuple FOR EACH STATEMENT BEGIN NewTuple.last-modified = sysdate; END;

Matthew P. Johnson, OCL1, CISDD CUNY, F Triggers: Row-level example MovieExec(name, address, cert#, netWorth) “If someone decreases a movie executive’s net worth, I want the database to reset itself to the previous net worth.” CREATE TRIGGER NetWorthTrigger AFTER UPDATE OF netWorth ON MovieExec REFERENCING NEW ROW AS NewTuple OLD ROW AS OldTuple FOR EACH ROW WHEN (OldTuple.netWorth>NewTuple.netWorth) UPDATE MovieExec SET netWorth = oldTuple.netWorth WHERE cert# = newTuple.cert#) CREATE TRIGGER NetWorthTrigger AFTER UPDATE OF netWorth ON MovieExec REFERENCING NEW ROW AS NewTuple OLD ROW AS OldTuple FOR EACH ROW WHEN (OldTuple.netWorth>NewTuple.netWorth) UPDATE MovieExec SET netWorth = oldTuple.netWorth WHERE cert# = newTuple.cert#)

Matthew P. Johnson, OCL1, CISDD CUNY, F Triggers: Table-level example MovieExec(name, address, cert#, netWorth) “If someone updates the net worth of one movie exec so that the average net worth of all movie execs becomes less than $50,000, I want the database to reset itself.” CREATE TRIGGER AvgNetWorthTrigger AFTER UPDATE OF netWorth ON MovieExec REFERENCING OLD TABLE AS OldStuff, NEW TABLE AS NewStuff FOR EACH STATEMENT WHEN (50000 > (SELECT AVG(netWorth) FROM MovieExec)) BEGIN DELETE FROM MovieExec WHERE (Name, address, cert#, netWorth) IN NewStuff; INSERT INTO MovieExec (SELECT * FROM OldStuff); END; CREATE TRIGGER AvgNetWorthTrigger AFTER UPDATE OF netWorth ON MovieExec REFERENCING OLD TABLE AS OldStuff, NEW TABLE AS NewStuff FOR EACH STATEMENT WHEN (50000 > (SELECT AVG(netWorth) FROM MovieExec)) BEGIN DELETE FROM MovieExec WHERE (Name, address, cert#, netWorth) IN NewStuff; INSERT INTO MovieExec (SELECT * FROM OldStuff); END;

Matthew P. Johnson, OCL1, CISDD CUNY, F Mutating Table Errors It’s generally impossible to a row-level trigger to modify or query the table that triggered it Does not apply to statement-level triggers Can do the equiv by creating a complicated statement-level trigger Won’t discuss…

Matthew P. Johnson, OCL1, CISDD CUNY, F Intermission Go over previous labs Begin lab… Break

Matthew P. Johnson, OCL1, CISDD CUNY, F Transactions So far, have simply issued commands  Ignored xacts Recall, though: an xact is an operation/set of ops executed atomically  In one instant ACID test:  Xacts are atomic  Each xact (not each statement) must leave the DB consistent

Matthew P. Johnson, OCL1, CISDD CUNY, F Default xact behavior An xact begins upon login By default, xact lasts until logoff  Except for DDL statements  They automatically commit Examples with two views of emp…

Matthew P. Johnson, OCL1, CISDD CUNY, F Direct xact instructions At any point, may explicitly COMMIT:  SQL> COMMIT;  Saves all statements entered up to now  Begins new xact Conversely, can ROLLBACK  SQL> ROLLBACK;  Cancels all statements entered since start of xact Example: delete from emp; or delete junk;

Matthew P. Johnson, OCL1, CISDD CUNY, F Direct xact instructions Remember, DDL statements are auto- committed  They cannot be rollbacked Examples: Q: Why doesn’t rollback “work”? drop table junk; rollback; drop table junk; rollback; truncate table junk; rollback; truncate table junk; rollback;

Matthew P. Johnson, OCL1, CISDD CUNY, F Savepoints Xacts are atomic Can rollback to beginning of current xact But might want to rollback only part way Make 10 changes, make one bad change Want to: roll back to before last change Don’t have Word-like multiple undo  But do have savepoints

Matthew P. Johnson, OCL1, CISDD CUNY, F Savepoints Create a savepoint: emp example: --changes SAVEPOINT sp1; --changes SAVEPOINT sp2; --changes SAVEPOINT sp3 --changes ROLLBACK TO sp2; ROLLBACK TO sp1; --changes SAVEPOINT sp1; --changes SAVEPOINT sp2; --changes SAVEPOINT sp3 --changes ROLLBACK TO sp2; ROLLBACK TO sp1; SAVEPOINT savept_name; Can skip savepoints But can ROLLBACK only backwards Can ROLLBACK only to last COMMIT

Matthew P. Johnson, OCL1, CISDD CUNY, F AUTOCOMMIT Finally, can turn AUTOCOMMIT on:  SQL> SET AUTOCOMMIT ON; Then each statement is auto-committed as its own xact  Not just DDL statements

Matthew P. Johnson, OCL1, CISDD CUNY, F New topic: the bulk loader To insert data, can insert rows one at a time with INSERT INTO VALUES(<>) If data is in/can be computed from other tables, can use  INSERT INTO SELECT … Often, have text file of data Oracle’s bulk loader will parse file and insert all into the database

Matthew P. Johnson, OCL1, CISDD CUNY, F Using the bulk loader The bulk loader takes two files:  The data file  The control file, specifying how to load the data Control file form: LOAD DATA INFILE INTO TABLE FIELDS TERMINATED BY ' ' ( ) LOAD DATA INFILE INTO TABLE FIELDS TERMINATED BY ' ' ( )

Matthew P. Johnson, OCL1, CISDD CUNY, F The control file Default data file extension:.dat Default control file extension:.ctl If APPEND is omitted, the table must be empty, else error Attribute list is comma-separated, but order doesn’t matter Separator can be multi-char LOAD DATA INFILE INTO TABLE FIELDS TERMINATED BY ' ' ( ) LOAD DATA INFILE INTO TABLE FIELDS TERMINATED BY ' ' ( )

Matthew P. Johnson, OCL1, CISDD CUNY, F The control file Example control file: LOAD DATA INFILE test.dat INTO TABLE test FIELDS TERMINATED BY '|' (i, s) LOAD DATA INFILE test.dat INTO TABLE test FIELDS TERMINATED BY '|' (i, s)

Matthew P. Johnson, OCL1, CISDD CUNY, F The data file Plain text file Each line  one row in the table Example data file: 1|foo 2|bar 3| baz 1|foo 2|bar 3| baz

Matthew P. Johnson, OCL1, CISDD CUNY, F Running the bulk loader The bulk loader is a command-line program sqlldr, separate from SQL*Plus: At cmd line, specify:  user/pass (pass is optional here)  the control file (which specifies data file), and  (optionally) a log file (dft ext:.log)  (optionally) a bad file (dft ext:.bad) c:\ sqlldr scott/tiger control=test log=test bad=bad

Matthew P. Johnson, OCL1, CISDD CUNY, F Data in the control file Can also merge the data and control file (onefile.ctl): The * indicates that the data is in this file LOAD DATA INFILE * INTO TABLE test FIELDS TERMINATED BY '|' (i, s) BEGINDATA 1|foo 2|bar 3| baz LOAD DATA INFILE * INTO TABLE test FIELDS TERMINATED BY '|' (i, s) BEGINDATA 1|foo 2|bar 3| baz

Matthew P. Johnson, OCL1, CISDD CUNY, F Loading dates In the control file’s attribute list, follow a data field with a date mask Date masks are case-INsensitive and include:  d- day  m - month  y - year withdates.ctl: LOAD DATA INFILE * INTO TABLE foo FIELDS TERMINATED BY '|' (i, d DATE 'dd-mm-yyyy') BEGINDATA 1| | LOAD DATA INFILE * INTO TABLE foo FIELDS TERMINATED BY '|' (i, d DATE 'dd-mm-yyyy') BEGINDATA 1| |

Matthew P. Johnson, OCL1, CISDD CUNY, F Loading timestamps Similar to dates but includes more chars:  Mi – minutes  ss – seconds  hh – hour  hh24: 24-hour hour  ff – millisecond (fractional seconds) withtimestamps.ctl: LOAD DATA INFILE * APPEND INTO TABLE ts FIELDS TERMINATED BY ',' (s, t timestamp 'yyyymmddhh24miss.ff' ) BEGINDATA 1, , LOAD DATA INFILE * APPEND INTO TABLE ts FIELDS TERMINATED BY ',' (s, t timestamp 'yyyymmddhh24miss.ff' ) BEGINDATA 1, ,

Matthew P. Johnson, OCL1, CISDD CUNY, F Loading nulls Two adjacent separators are interpreted as a null value in the field: What if null in last field? Two options:  Put TRAILING NULLCOLS following field-term df  Append an extra field sep to end withnulls.ctl: 3||5 |2|4 1||6 ||7 3||5 |2|4 1||6 ||7 LOAD DATA INFILE * APPEND INTO TABLE nums FIELDS TERMINATED BY '|' TRAILING NULLCOLS (a,b,c) BEGINDATA 3||5 |2|4 1|2| 1|2|| LOAD DATA INFILE * APPEND INTO TABLE nums FIELDS TERMINATED BY '|' TRAILING NULLCOLS (a,b,c) BEGINDATA 3||5 |2|4 1|2| 1|2||

Matthew P. Johnson, OCL1, CISDD CUNY, F After Complete lab… Read XML and regex chapters for next time Vote early and vote often!