Power Points

advertisement
Chapter Thirteen
Sequences
Dr. Chitsaz
Objectives:
• Sequence objects
• Create and use sequences
• Application of sequences
Objects
• Object Types:
–
–
–
–
–
Table
View
Sequence
Index
Synonym
2
SEQUENCE
• Automatically generates sequence number
(For rows in tables)
• Is sharable among tables.
• Typically used to create a primary key
value (Unique numbers and may have gaps)
• Stored and generated independently of
tables. So the same sequence may be used in several
tables.
3
CREATE SEQUENCE:
CREATE SEQUENCE
sequence
[INCREMENT BY n] --negative number to decrement
[START With n]
[MAXVALUE n| NOMAXVALUE ]
[MINVALUE n| NOMINVALUE ]
[CYCLE | NOCYCLE ] --start over or not
[CACHE n | NOCACHE ]; --n numbers stored in memory
for efficiency; default is 20;
4
CREATE SEQUENCE:
Example:
CREATE SEQUENCE id_seq
INCREMENT
BY 1
START WITH 1000
MAXVALUE 99999
NOCACHE
NOCYCLE
;
5
CONFIRMING SEQUENCE:
Since it is an object, it can be query:
SELECT
FROM
sequence_name,
min_value,
max_value,
increment_by,
last_number --next number stored
user_sequences; -- or use SEQ
6
CONFIRMING SEQUENCE:
• NEXTVAL: --next available sequence number
• CURRVAL: --present value
• NEXTVAL & CURRVAL can not be used in:
•
•
•
•
•
•
•
SELECT list of a view
SELECT with distinct clause
SELECT with group by
SELECT having
SELECT order by
SELECT union/intersect/minus
Subquery in SELECT, INSERT, or UPDATE
7
USING A SEQUENCE:
• INSERT INTO
VALUES
student (id, name)
(id_seq.NEXTVAL,
'&name');
• View the current value of the sequence id_seq:
•
SELECT
id_seq.CURRVAL
FROM
dual;
8
USING A SEQUENCE:
SELECT id_seq.CURRVAL, id_seq.NEXTVAL
FROM
dual;
--if currval and nextval is used in the same query,
both return the same number.
9
USING A SEQUENCE:
INSERT INTO
VALUES
student_course (Id , C_num,
Dept_name)
(Stud_Seq.NEXTVAL,
Course_Seq.NEXTVAL ,
’&Dept_name’);
10
Gaps in sequence values:
it is possible to have gaps in the sequence:
• A rollback
• The system crashes
• A sequence is used in another table
11
Modifying a sequence:
ALTER SEQUENCE id_seq
INCREMENT BY 10
START WITH 1000
MAXVALUE 99999
NOCACHE
NOCYCLE;
12
Rules for Modifying a Sequence:
• You must be the owner or have the ALTER
privilege
• Only future sequence numbers are affected
• To restart a sequence, the sequence must
be dropped and recreated.
13
Dropping a Sequence:
• DROP SEQUENCE id_seq;
14
Question?
• id_seq is 150; We would like to change the
lastvalue to 350.
15
Download