Sie sind auf Seite 1von 44

Oracle Sequences

• Allow users to provide automatically-assigned unique numbers to columns


in one or more tables.
• Are independent objects in the database. (they are not a data type)
• Have a name and can be used anywhere a value is expected.
• They are not tied up to a table or column
• Generate numeric value that can be assigned to any column in any table
• The table attribute to which you assigned a value based on a sequence
can be edited and modified
• Can be created and deleted anytime
• You can use one sequence for to create unique values in one or more
tables
• You can always issue an INSERT statement without using the sequence.
• You can always drop a sequence from a database. This doesn’t affect the
value already inserted by the sequence.

1
Oracle Sequence Syntax
• Creating an Oracle Sequence
– CREATE SEQUENCE sequence_name [START WITH n] [INCREMENT
BY n] [CACHE | NOCACHE]
– sequence_name - is the name of the sequence
– n - is an integer value that could be positive or negative
– START WITH – specifies the initial sequence value. (default value is 1)
– INCREMENT BY determines the value by which the sequence is
incremented. (default is 1)
– CATCHE or NOCATCHE clause indicates whether or not oracle will
preallocate sequence numbers in memory. (Oracle preallocates 20 by
default)
– Eg. CREATE SEQUENCE CUS_CODE_SEQ START WITH 20010
NOCACHE;
• Deleting an Oracle Sequence
– DROP SEQUENCE sequence_name;
– Eg. DROP SEQUENCE CUS_CODE_SEQ;

2
Inserting Oracle Sequences
• Checking for available Oracle Sequences
– SELECT * FROM USER_SEQUENCES;
• Inserting values into a table with Oracle
Sequence
• Eg.
– INSERT INTO CUSTOMER
VALUES(CUS_CODE_SEQ.NEXTVAL, ‘Connery’,
‘Sean’, NULL, ‘615’, ‘898-2008’, 0.00);

3
Note about sequences
• NEXTVAL always retrieves the next available value from
sequence
• Each time you use NEXTVAL, the sequence is
incremented.
• Once a sequence value is used (through NEXTVAL), it
cannot be used again. Even if, your SQL statement rolls
back for some reason. The result may look like the
sequence skips a number. (no re-use characteristic)
• CURRVAL retrieves the current value of a sequence, i.e.
the last sequence number used
• You can’t use CURRVAL unless a NEXTVAL has been
previously issued in the same session.
• The main use of CURRVAL is to enter rows in dependent
tables
4
Using Sequences CURRVAL

INSERT INTO CUSTOMER


VALUES(CUS_CODE_SEQ.NEXTVAL, ‘Connery’, ‘Sean’,
NULL, ‘615’, ‘898-2008’, 0.00);
INSERT INTO INVOICE
VALUES(2000,CUS_CODE_SEQ.CURRVAL, SYSDATE);

5
Procedural SQL (PL/SQL)

• Used to alleviate the procedural functionality limitations of


basic SQL, such as conditional execution, looping
operations, declaring variables, etc.
• End users can use PL/SQL to create:
– Anonymous PL/SQL blocks
– Triggers
– Stored procedures
– PL/SQL functions
• Note: the following discussions, syntaxes, and examples
assume the use of Oracle DBMS as the use of PL/SQL is
not yet standardized to all DBMSs.

6
Anonymous PL/SQL blocks
• This procedure doesn’t have a name and executes
whenever users create the procedure and hit execute
button. Following the PL/SQL block’s execution, you will
see the message “PL/SQL procedure successfully
completed.” Or an error message will be displayed.
• You can specify your own specific messages. To do this
follow the following steps.
• SET SERVEROUTPUT ON to receive message from the
server you can turn it off by similar syntax if you want to
stop receiving messages from the server.
• To send messages from the PL/SQL block to the
SQL*Plus console, use the DBMS_OUTPUT.PUT_LINE
function.
• You can use the syntax SHOW ERRORS; to see more
detailed error message.
7
Note About PL/SQL
• Each statement inside the PL/SQL code must end with a
semi-colon “;”.
• PL/SQL blocks can contain only standard SQL data
manipulation language (DML) commands such as select,
update, and delete. The use of DDL commands is not
directly supported in a PL/SQL.
• The SELECT statement uses the INTO keyword to assign
the output of the query to a PL/SQL variable.
– You can only use the INTO keyword inside a PL/SQL block of code
– If the SELECT statement returns more than one value, you will get
an error message.
• Use double dashes (--) for comments within the PL/SQL
block
8
PL/SQL Basic Data Types

9
Anonymous Block Syntax
[DECLARE]
[variable_name data type[:= initial_value]];
BEGIN
PL/SQL or SQL statements;
…..
END;
/
• Notice the procedure ends with a forward slash.

10
PL/SQL
• Conditional execution syntax:
IF <condition> THEN
<perform procedure>
[ELSE]
<perform alternate procedure>
END IF;
• Looping:
– While-loop
WHILE <condition> LOOP
<perform procedure>
END LOOP;
– Or do-while
DO WHILE
<perform procedure>
END DO;

11
Anonymous Block Examples:
1) Add a new invoice row into invoice table and display
“One invoice entry added!” message if entry is
successful.

BEGIN
INSERT INTO INVOICE
VALUES(10010,10015,SYSDATE);
DBMS_OUTPUT.PUT_LINE(‘New Invoice
Added!’);
END;
/
12
Examples Cont’d
1) display number of products with prices within the interval of 50 between the min and
max prices. Minimum starting from o and max starting with 50.

DECLARE
TEMP_MIN NUMBER(3) := 0;
TEMP_MAX PRODUCT.P_PRICE%TYPE := 50;
TEMP_COUNT NUMBER(2) := 0;
BEGIN
WHILE TEMP_MAX < 300 LOOP
SELECT COUNT(P_CODE) INTO TEMP_COUNT FROM PRODUCT
WHERE P_PRICE BETWEEN TEMP_MIN AND TEMP_MAX;
DBMS_OUTPUT.PUT_LINE(‘There are ’ || TEMP_COUNT || ‘Products with
price between ’ || TEMP_MIN || ‘ and ’ || TEMP_MAX);
TEMP_MIN := TEMP_MAX + 1;
TEMP_MAX := TEMP_MAX + 50;
END LOOP;
END;
/

13
Stored Procedures
• A stored procedure is a named collection of
procedural and SQL statements stored in the
database.
• One of the major advantages is that they can be
used to encapsulate and represent business
transactions.
• Eg. We can represent a product sale, a credit
update, or the addition of a new customer with a
single procedure, and execute them as a single
transaction.

14
Advantages
1) Stored procedures substantially reduce network
traffic and increase performance. Because they
are stored at the server, there is no transmission
of individual SQL statements over the network.
Thus improves system performance.
2) Stored procedures help reduce code duplication
by means of code isolation and code sharing
(creating unique PL/SQL modules that are called
by application programs), thereby minimizing the
chance of errors and the cost of application
development and maintenance.
15
Stored Procedure Syntax
CREATE OR REPLACE PROCEDURE procedure_name
[(argument [IN/OUT] data-type,...)] [IS/AS] [variable_name
data-type [:= initial_value]]
BEGIN
PL/SQL or SQL statements;
…..
END;
/

16
Note About Stored Procedures
• Argument specifies the parameters that are
passed to the stored procedure. A stored
procedure could have zero or more arguments or
parameters.
• IN/OUT indicates whether the parameter is for
input or for output or both
• Variables can be declared between the keyword
IS and BEGIN.
• To execute the stored procedure you must use
the following syntax:
– EXEC procedure_name[(parameter_list)];

17
Stored Procedure #1
CREATE OR REPLACE PROCEDURE Prc_Prod_Discount (Temp_Disc IN
Number)
AS
BEGIN
-- Test if value entered is a percentage i.e between o and 1

IF ((Temp_Disc <= 0) OR (Temp_Disc >= 1)) THEN


DBMS_OUTPUT.PUT_LINE(‘Error: Value must be greater than
0 and less than 1’);
ELSE
UPDATE PRODUCT
SET P_DISCOUNT = P_DISCOUNT + Temp_Disc
WHERE P_QOH >= P_MIN * 2;
DBMS_OUTPUT.PUT_LINE (‘* * Update Finished * * ’);
END IF;
END;
/

18
Stored Procedure #2
CREATE OR REPLACE PROCEDURE NEW_CLIENT (C_FNAME IN VARCHAR, C_LNAME IN
VARCHAR, C_TITLE IN VARCHAR, C_PHONE IN VARCHAR, C_EMAIL IN
VARCHAR, C_CONNUM IN NUMBER)
AS
TEMP_MAX NUMBER;
TEMP_CONMAX NUMBER;
BEGIN
SELECT Count(*) INTO TEMP_MAX FROM REGISTRATION
WHERE CON_NUM = C_CONNUM;
SELECT CON_MAXCLIENTS INTO TEMP_CONMAX FROM CONTRACT
WHERE CON_NUM = C_CONNUM;
IF TEMP_MAX >= TEMP_CONMAX THEN
Dbms_Output.PUT_LINE (' Maximum Number of Clients Already
Registered!');
ELSE
INSERT INTO CLIENT (CLT_NUM, CLT_FNAME, CLT_LNAME,
CLT_TITLE,CLT_PHONE, CLT_EMAIL)
VALUES(CLIENT_NUM_SEQ.NEXTVAL, C_FNAME, C_LNAME, C_TITLE,
C_PHONE, C_EMAIL);
INSERT INTO REGISTRATION (CLT_NUM, CON_NUM, REG_DATE) VALUES
(CLIENT_NUM_SEQ.CURRVAL, C_CONNUM, SYSDATE);
Dbms_Output.PUT_LINE (' The Client Was SuccessfulLY
Registered.');
END IF;
END; 19
/
Trigger
• Trigger
– Block of PL/SQL code that executes
automatically when a specified condition
occurs.
– Triggering Condition
• DML statement (INSERT, UPDATE, DELETE)
• BEFORE or AFTER
• Statement level or Row level execution
– Each database table may have one or more
triggers
20
Trigger
• Triggers typically involve an event,
condition and an action. Sometimes called
(event-condition-action rules)
Example-
• Event: insertion of a row into enrollment table
• Condition: seats remaining column is greater
than 0
• Action: decrement the seats remaining column
after insertion

21
Trigger Uses
• Auditing Purposes
• Automatic generation of derived column
values
• Enforcement of business or security
constraints
• Creating replica tables for backup
purposes

22
DML Statement
• DML = Data Manipulation Language
– Any SQL statement that retrieves or changes the
contents of a table
• INSERT = add one or more records to the table
• UPDATE = modify the contents of one or more records
• DELETE = remove one or more records
– The trigger is associated with a specific table
– If UPDATE is used, you have the option of associating
the trigger with specific, individual attributes (using
UPDATE OF)
– Does NOT include SELECT queries
• Technically, SELECT queries are DML, but Oracle does not
support triggers for SELECT queries.

23
BEFORE or AFTER
• BEFORE
– The trigger is executed before the DML statement that
fired it is written to the database.
– Allows the trigger to manipulate values before they
are written to the database.
– Can be used to ensure that a consistent state is
possible.
• AFTER
– The trigger is executed after the DML statement that
fired it is written to the database.
– Allows the database to return to a consistent state
before the trigger is executed.

24
Statement Level or Row Level
Execution
• Statement Level
– Default level if none is specified
– Trigger is executed only once when the DML
statement is executed
– Often used for auditing purposes
• Row Level
– Specified with the key phrase FOR EACH ROW
– Trigger is executed once for each row affected by the
DML statement
– Allows viewing and manipulating the values of the
data that are being affected

25
Trigger
• A trigger is invoked before or after a row is
inserted, updated, or deleted
• A trigger is associated with a database
table
• Each database table may have one or
more triggers
• A trigger is executed as part of the
transaction that triggered it.
26
Sequence of Execution
1. User Issues a DML command, such as
UPDATE EMPLOYEE SET EMP_SAL = EMP_SAL + 500;
2. Oracle checks that the command is valid (no syntax
errors, etc.)
3. Oracle manipulates the data in memory according to the
DML command.
4. Oracle checks for any BEFORE triggers that should be
executed.
5. BEFORE triggers executed.
6. User DML command written to the database.
7. Oracle checks for any AFTER triggers that should be
executed.
8. AFTER triggers executed.
27
BEFORE Trigger Execution
(Update Command)

:NEW.P_MIN := 8;
P_CODE P_DESCRIPT
11QER/31 Saw Blade
P_MIN P_QOH P_PRICE
8
5 10 9.95

P_CODE P_DESCRIPT
11QER/31 Saw Blade
P_MIN P_QOH P_PRICE
5 8 9.95

UPDATE Command Executed

UPDATE PRODUCT Database


SET P_QOH = 10
WHERE P_CODE = ’11QER/31’; 28
BEFORE Trigger Execution
(Insert Command)

:NEW.P_MIN := 5;
P_CODE P_DESCRIPT
12345 Saw Blade
P_MIN P_QOH P_PRICE
Null
5 15 8.99

P_CODE P_DESCRIPT
Null Null
P_MIN P_QOH P_PRICE
Null Null Null

INSERT Command Executed

INSERT INTO PRODUCT VALUES ( Database


‘12345’, ‘Saw blade’, Null, 15, 8.99);
29
:OLD and :NEW
• :OLD
– Contains all the values from the entire row
being manipulated
– Read only
• :NEW
– Contains all the values from the entire row
being manipulated
– Read and Write with BEFORE trigger
– Read only with AFTER trigger

30
Trigger Syntax
CREATE OR REPLACE TRIGGER trigger_name
[BEFORE/AFTER] [DELETE/ INSERT/ UPDATE OF
column_name] ON table_name
[FOR EACH ROW]
[DECLARE]
[variable_name data type[:= initial_value]];
BEGIN
PL/SQL or SQL statements;
…..
END;
/

31
Trigger #1
• Create a trigger for the LINE table so that
if the user does not specify a
LINE_PRICE, the P_Price from the
PRODUCT table is used as the
LINE_PRICE.

32
Trigger #1 Triggering Condition
Questions
• What DML should be the triggering
condition?
• Should it be a BEFORE trigger or AFTER
trigger?
• Statement Level or Row Level?

33
Trigger #1 Triggering Condition
Decisions
• Use INSERT or UPDATE OF LINE_PRICE
because either of these could result in a NULL
price.
• Use BEFORE because the trigger will need to
modify the values being written (:NEW).
• Use ROW Level because the trigger will need to
work with the row values.

34
Trigger #1 Logic
• Check to see if the LINE_PRICE being
entered is null.
• If the LINE_PRICE is null
– Get the P_PRICE for the product being
ordered.
• Note to self: I need to have a variable to store this
number in when I look it up.
– Make the new LINE_PRICE equal to the
P_PRICE found above.
35
Trigger #1 Solution
CREATE OR REPLACE TRIGGER TRG_LINE_PRICE
BEFORE INSERT OR UPDATE OF LINE_PRICE ON LINE
FOR EACH ROW
DECLARE
TEMP_PRICE NUMBER;
BEGIN
IF :NEW.LINE_PRICE IS NULL THEN
SELECT P_PRICE INTO TEMP_PRICE
FROM PRODUCT
WHERE P_CODE = :NEW.P_CODE;
:NEW.LINE_PRICE := TEMP_PRICE;
END IF;
END;
/

36
Trigger #2
• Create a trigger such that a adding a new
line item, or a change to the line units or
line price of an existing line item, results in
an appropriate update to the customer’s
balance.

37
Trigger #2 Triggering Condition
Questions
• What DML should be the triggering
condition?
• Should it be a BEFORE trigger or AFTER
trigger?
• Statement Level or Row Level?

38
Trigger #2 Triggering Condition
Decisions
• Use INSERT or UPDATE OF LINE_PRICE,
LINE_UNITS because any of these could result
in a change to the customer’s balance.
• Can use AFTER because the trigger will not
need to modify the values being written (:NEW).
• Use ROW Level because the trigger will need to
work with the row values.

39
Trigger #2 Logic
• Determine the change in value for the line item (line units * line
price).
– Note, the customer balance may be impacted by payments not recorded
in this system, so the balance is not just the sum of all line item totals.
– Calculate old line item total (old line_units * old line_price)
• If the old values are NULL because of an INSERT, then make it zero
– Calculate new line item total (new line_units * new line_price)
– Subtract to get the difference
• Add the difference to the customer’s balance.
– Determine which customer this line item belongs to.
– Update the customer table with the difference calculated above.
– Note that :OLD and :NEW will only contain the data from the triggering
DML statement.

40
Trigger #2 Solution
CREATE OR REPLACE TRIGGER TRG_CUSTOMER_BALANCE
AFTER INSERT OR UPDATE OF LINE_UNITS, LINE_PRICE ON LINE
FOR EACH ROW
DECLARE
TEMP_CUS_CODE CUSTOMER.CUS_CODE%TYPE;
TEMP_NEW_TOTAL NUMBER;
TEMP_OLD_TOTAL NUMBER;
TEMP_DIFF NUMBER;
BEGIN
TEMP_OLD_TOTAL := :OLD.LINE_UNITS * :OLD.LINE_PRICE;
IF TEMP_OLD_TOTAL IS NULL THEN
TEMP_OLD_TOTAL := 0;
END IF;
TEMP_NEW_TOTAL := :NEW.LINE_UNITS * :NEW.LINE_PRICE;
TEMP_DIFF := TEMP_NEW_TOTAL – TEMP_OLD_TOTAL;
SELECT CUS_CODE INTO TEMP_CUS_CODE
FROM INVOICE
WHERE INV_NUMBER = :NEW.INV_NUMBER;
UPDATE CUSTOMER
SET CUS_BALANCE = CUS_BALANCE + TEMP_DIFF
WHERE CUS_CODE = TEMP_CUS_CODE;
END;
/
41
Trigger #3
• Create a trigger that updates the reorder
column of a product table automatically
whenever inserting or updating the
quantity on hand column results less than
or equal to the minimum number required
for a particular product

42
Trigger #3 Solution
CREATE OR REPLACE TRIGGER TRG_PRODUCT_REORDER
AFTER INSERT OR UPDATE OF P_QOH ON PRODUCT
BEGIN
UPDATE PRODUCT
SET P_REORDER = 1
WHERE P_QOH <= P_MIN;

END;
/

43
Testing Trigger #3
1) Update the P_QOH column of PRODUCT
table to be less than P_MIN
2) How about changing the value of P_MIN
column of PRODUCT table to be greater than
P_QOH?
- Fix the problem by adding P_MIN on the
column name declaration of the trigger.

 Go through all the examples above &…


 *** Finish all questions of Exercise-2 ***
44

Das könnte Ihnen auch gefallen