Bordoloi and BockCopyright 2004 Prentice Hall, Inc.8-1 COS 346 Day 17.

106
Bordoloi and Bordoloi and Bock Bock Copyright 2004 Prentice Hall, Inc. 8-1 COS 346 COS 346 Day 17 Day 17
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    216
  • download

    0

Transcript of Bordoloi and BockCopyright 2004 Prentice Hall, Inc.8-1 COS 346 Day 17.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-1

COS 346COS 346

Day 17Day 17

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-2

AgendaAgenda• Assignment 6 CorrectedAssignment 6 Corrected

– 5 A’s, 1 C & 1 D (no outputs for C & D) 5 A’s, 1 C & 1 D (no outputs for C & D) • Assignment 7 PostedAssignment 7 Posted

– Due April 5Due April 5– 4 (5?) more to go4 (5?) more to go

• Assignment 8 PostedAssignment 8 Posted– Due April 9Due April 9– 3 (4?) more to go3 (4?) more to go

• Quiz 2 will April 12 Quiz 2 will April 12 – DP 7 & 8, SQL 2-10DP 7 & 8, SQL 2-10– There will only be 3 exams (3 @ 10% instead of 4 @ 7.5%) There will only be 3 exams (3 @ 10% instead of 4 @ 7.5%)

• Capstone Progress Reports Due April 5Capstone Progress Reports Due April 5• Make sure to check corrections for Oracle text for WebCTMake sure to check corrections for Oracle text for WebCT

– Miss wording of Q 14 on page 89Miss wording of Q 14 on page 89• Today we will discussToday we will discuss

– Views Synonyms and sequences Views Synonyms and sequences – Begin SQL*Plus reports Begin SQL*Plus reports

• We will be in the Oracle SQL text for the next 1+ weeksWe will be in the Oracle SQL text for the next 1+ weeks

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-3

End of days? (subject to change) End of days? (subject to change) • April 2April 2

– SQL Chap 8 & 9SQL Chap 8 & 9• April 5April 5

– SQL Chap 9 SQL Chap 9 – SQL Chap 10 SQL Chap 10 – Assignment 7 dueAssignment 7 due

• April 9April 9– DP Chap 9DP Chap 9– Assignment 8 dueAssignment 8 due

• April 12April 12– Quiz 2Quiz 2– DP chap 10DP chap 10– SQL Chap 12SQL Chap 12

• April 16April 16– SQL Chap 11SQL Chap 11– DP Chap 12 DP Chap 12 – Assignment 9 dueAssignment 9 due

• April 19April 19– DP Chap 13 DP Chap 13

• April 23April 23– DP Chap 14DP Chap 14– Assignment 10 DueAssignment 10 Due

• April 30April 30– DP Chap 15DP Chap 15– ReviewReview

• May 3May 3– Quiz 3Quiz 3– Assignment 11 DueAssignment 11 Due

• May 9May 9– 10 AM10 AM– Capstone presentations Capstone presentations

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-4

CHAPTER 8:CHAPTER 8:VIEWS, SYNONYMS, VIEWS, SYNONYMS,

AND SEQUENCESAND SEQUENCES

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-5

VIEWSVIEWS

• A database view is a A database view is a logical logical oror virtual table virtual table based on a query.based on a query.

• It is useful to think of a It is useful to think of a viewview as a stored query. as a stored query.

• Views are created through use of a CREATE Views are created through use of a CREATE VIEW command that incorporates use of the VIEW command that incorporates use of the SELECT statement. SELECT statement.

• Views are queried just like tables. Views are queried just like tables.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-6

VIEWSVIEWS

CREATE VIEW employee_parking CREATE VIEW employee_parking (parking_space, last_name, (parking_space, last_name,

first_name, ssn) ASfirst_name, ssn) AS

SELECT emp_parking_space, SELECT emp_parking_space, emp_last_name, emp_first_name, emp_last_name, emp_first_name, emp_ssn emp_ssn

FROM employeeFROM employee

ORDER BY emp_parking_space;ORDER BY emp_parking_space;

View Created.View Created.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-7

VIEWSVIEWS

SELECT *SELECT *

FROM employee_parking;FROM employee_parking;

  

PARKING_SPACE LAST_NAME FIRST_NAME SSNPARKING_SPACE LAST_NAME FIRST_NAME SSN

------------- ---------- ----------- --------------------- ---------- ----------- --------

1 Bordoloi Bijoy 9996666661 Bordoloi Bijoy 999666666

3 Joyner Suzanne 9995555553 Joyner Suzanne 999555555

32 Zhu Waiman 99944444432 Zhu Waiman 999444444

more rows are displayed…more rows are displayed…

  • Notice that the only columns in the query are Notice that the only columns in the query are

those defined as part of the view. those defined as part of the view.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-8

VIEWSVIEWS

• Additionally, we have renamed the columns in the Additionally, we have renamed the columns in the view so that they are slightly different than the view so that they are slightly different than the column names in the underlying employee table.column names in the underlying employee table.

• Further, the rows are sorted by Further, the rows are sorted by parking_spaceparking_space column even though there is no ORDER BY in the column even though there is no ORDER BY in the SELECT command used to access the view. SELECT command used to access the view.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-9

CREATING A VIEWCREATING A VIEW

• CREATE VIEW SyntaxCREATE VIEW Syntax

CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW <view name> CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW <view name> [(column alias name….)] AS <query> [WITH [CHECK OPTION] [READ [(column alias name….)] AS <query> [WITH [CHECK OPTION] [READ ONLY] [CONSTRAINT]];ONLY] [CONSTRAINT]];

• The OR REPLACE option is used to create a view that The OR REPLACE option is used to create a view that already exists. This option is useful for modifying an already exists. This option is useful for modifying an existing view without having to drop or grant the privileges existing view without having to drop or grant the privileges that system users have acquired with respect to the view.that system users have acquired with respect to the view.

• If you attempt to create a view that already exists without If you attempt to create a view that already exists without using the OR REPLACE option, Oracle will return the using the OR REPLACE option, Oracle will return the ORA-00955: ORA-00955: name is already used by an existing objectname is already used by an existing object error message and the CREATE VIEW command will fail. error message and the CREATE VIEW command will fail.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-10

CREATING A VIEWCREATING A VIEW

• The FORCE option allows a view to be created even if a base The FORCE option allows a view to be created even if a base table that the view references does not already exist.table that the view references does not already exist.

• This option is used to create a view prior to the actual This option is used to create a view prior to the actual creation of the base tables and accompanying data. Before creation of the base tables and accompanying data. Before such a view can be queried, the base tables must be created such a view can be queried, the base tables must be created and data must be loaded into the tables. This option can also and data must be loaded into the tables. This option can also be used if a system user does not currently have the privilege be used if a system user does not currently have the privilege to create a view. to create a view.

• The NOFORCE option is the opposite of FORCE and allows The NOFORCE option is the opposite of FORCE and allows a system user to create a view if they have the required a system user to create a view if they have the required permissions to create a view, and if the tables from which the permissions to create a view, and if the tables from which the view is created already exist. This is the default option.view is created already exist. This is the default option.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-11

CREATING A VIEWCREATING A VIEW

• The WITH READ ONLY option allows creation of a view The WITH READ ONLY option allows creation of a view that is read-only. You cannot use the DELETE, INSERT, that is read-only. You cannot use the DELETE, INSERT, or UPDATE commands to modify data for the view. or UPDATE commands to modify data for the view.

• The WITH CHECK OPTION clause allows rows that can The WITH CHECK OPTION clause allows rows that can be selected through the view to be updated. It also enables be selected through the view to be updated. It also enables the specification of constraints on values.the specification of constraints on values.

• The CONSTRAINT clause is used in conjunction with the The CONSTRAINT clause is used in conjunction with the WITH CHECK OPTION clause to enable a database WITH CHECK OPTION clause to enable a database administrator to assign a unique name to the CHECK administrator to assign a unique name to the CHECK OPTION. If the DBA omits the CONSTRAINT clause, OPTION. If the DBA omits the CONSTRAINT clause, Oracle will automatically assign the constraint a system-Oracle will automatically assign the constraint a system-generated name that will not be very meaningful.generated name that will not be very meaningful.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-12

ExampleExample

CREATE VIEW empview7 AS CREATE VIEW empview7 AS

SELECT emp_ssn, emp_first_name, emp_last_nameSELECT emp_ssn, emp_first_name, emp_last_name

FROM employeeFROM employee

WHERE emp_dpt_number=7;WHERE emp_dpt_number=7;

View created.View created.

•A simple query of the A simple query of the empview7empview7 shows the following data. shows the following data.

SELECT *SELECT *

FROM empview7;FROM empview7;

EMP_SSN EMP_FIRST_NAME EMP_LAST_NAMEEMP_SSN EMP_FIRST_NAME EMP_LAST_NAME

--------- ------------------------- ---------------------------------- ------------------------- -------------------------

999444444 Waiman Zhu999444444 Waiman Zhu

999111111 Douglas Bock999111111 Douglas Bock

999333333 Dinesh Joshi999333333 Dinesh Joshi

999888888 Sherri Prescott999888888 Sherri Prescott

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-13

ExampleExample

• It is also possible to create a view that has exactly the It is also possible to create a view that has exactly the same structure as an existing database table. same structure as an existing database table.

• The view named The view named dept_viewdept_view shown next has exactly shown next has exactly the same structure as the same structure as departmentdepartment table. table.

CREATE VIEW dept_view AS CREATE VIEW dept_view AS

SELECT * SELECT *

FROM department;FROM department;

View created.View created.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-14

ExampleExample

• We can recreate the view by using the OR REPLACE clause We can recreate the view by using the OR REPLACE clause to create a view that is to create a view that is read-onlyread-only by specifying a WITH by specifying a WITH READ ONLY clause. READ ONLY clause.

• The new version of The new version of dept_viewdept_view will restrict data manipulation will restrict data manipulation language operations on the view to the use of the SELECT language operations on the view to the use of the SELECT command.command.

CREATE OR REPLACE VIEW dept_view AS CREATE OR REPLACE VIEW dept_view AS

SELECT * SELECT *

FROM department WITH READ ONLY CONSTRAINT FROM department WITH READ ONLY CONSTRAINT vw_dept_view_read_only;vw_dept_view_read_only;

View created.View created.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-15

FUNCTIONS AND VIEWS – A JOIN VIEWFUNCTIONS AND VIEWS – A JOIN VIEW

• In addition to specifying columns from existing In addition to specifying columns from existing tables, you can use single row functions consisting of tables, you can use single row functions consisting of number, character, date, and group functions as well number, character, date, and group functions as well as expressions to create additional columns in views. as expressions to create additional columns in views.

• This can be extremely useful because the system This can be extremely useful because the system user will have access to data without having to user will have access to data without having to understand how to use the underlying functions. understand how to use the underlying functions.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-16

ExampleExampleCREATE OR REPLACE VIEW dept_salary CREATE OR REPLACE VIEW dept_salary

(name, min_salary, max_salary, avg_salary) AS (name, min_salary, max_salary, avg_salary) AS

SELECT d.dpt_name, MIN(e.emp_salary), SELECT d.dpt_name, MIN(e.emp_salary),

MAX(e.emp_salary), AVG(e.emp_salary)MAX(e.emp_salary), AVG(e.emp_salary)

FROM employee e, department dFROM employee e, department d

WHERE e.emp_dpt_number=d.dpt_noWHERE e.emp_dpt_number=d.dpt_no

GROUP BY d.dpt_name;GROUP BY d.dpt_name;

View created.View created.

SELECT * SELECT *

FROM dept_salary;FROM dept_salary;

NAME MIN_SALARY MAX_SALARY AVG_SALARYNAME MIN_SALARY MAX_SALARY AVG_SALARY

------------------------- ------------------ ------------------ ------------------------------------------- ------------------ ------------------ ------------------

Admin and Records 25000 Admin and Records 25000 43000 43000 3100031000

Headquarters Headquarters 55000 55000 55000 55000 5500055000

Production Production 25000 25000 43000 43000 3400034000

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-17

VIEW STABILITYVIEW STABILITY

• A view does not actually store any data. The A view does not actually store any data. The data needed to support queries of a view are data needed to support queries of a view are retrieved from the underlying database tables retrieved from the underlying database tables and displayed to a result table whenever a and displayed to a result table whenever a view is queried. The result table is only stored view is queried. The result table is only stored temporarily. temporarily.

• If a table that underlies a view is dropped, If a table that underlies a view is dropped, then the view is no longer valid. Attempting then the view is no longer valid. Attempting to query an invalid view will produce an to query an invalid view will produce an ORA-04063: view "VIEW_NAME" has errors ORA-04063: view "VIEW_NAME" has errors error message. error message.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-18

INSERTING , UPDATING, and DELETINGINSERTING , UPDATING, and DELETING TABLE ROWS THROUGH VIEWSTABLE ROWS THROUGH VIEWS

• You can insert a row if the view in use is one You can insert a row if the view in use is one that is updateable (not read-only). that is updateable (not read-only).

• A view is updateable if the INSERT command A view is updateable if the INSERT command does not violate any constraints on the does not violate any constraints on the underlying tables.underlying tables.

• This rule concerning constraint violations also This rule concerning constraint violations also applies to UPDATE and DELETE commands. applies to UPDATE and DELETE commands.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-19

ExampleExampleCREATE OR REPLACE VIEW dept_view ASCREATE OR REPLACE VIEW dept_view ASSELECT dpt_no, dpt_name SELECT dpt_no, dpt_name FROM department;FROM department;

INSERT INTO dept_view VALUES (18, 'Department 18');INSERT INTO dept_view VALUES (18, 'Department 18');INSERT INTO dept_view VALUES (19, 'Department 20');INSERT INTO dept_view VALUES (19, 'Department 20');

SELECT *SELECT *FROM dept_view;FROM dept_view;DPT_NO DPT_NAMEDPT_NO DPT_NAME------------ -------------------------------- -------------------- 7 Production7 Production 3 Admin and Records3 Admin and Records 1 Headquarters1 Headquarters 18 Department 1818 Department 18 19 Department 2019 Department 20

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-20

ExampleExample

UPDATE dept_view SET dpt_name = 'Department 19‘UPDATE dept_view SET dpt_name = 'Department 19‘

WHERE dpt_no = 19;WHERE dpt_no = 19;

1 row updated.1 row updated.

SELECT *SELECT *

FROM departmentFROM department

WHERE dpt_no >= 5;WHERE dpt_no >= 5;

DPT_NO DPT_NAME DPT_MGRSS DPT_MGR_SDPT_NO DPT_NAME DPT_MGRSS DPT_MGR_S

----------- -------------------- ------------------ ---------------------------- -------------------- ------------------ -----------------

7 Production 999444444 22-MAY-987 Production 999444444 22-MAY-98

18 Department 1818 Department 18

19 Department 1919 Department 19

more rows are displayed…more rows are displayed…

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-21

More ExamplesMore Examples

DELETE dept_view DELETE dept_view

WHERE dpt_no = 18 OR dpt_no = 19;WHERE dpt_no = 18 OR dpt_no = 19;

2 rows deleted.2 rows deleted.

SELECT *SELECT *

FROM department;FROM department;

DPT_NO DPT_NAME DPT_MGRSS DPT_MGR_SDPT_NO DPT_NAME DPT_MGRSS DPT_MGR_S

------------ ------------------------ ------------------ ---------------------------- ------------------------ ------------------ ----------------

7 Production 999444444 22-MAY-987 Production 999444444 22-MAY-98

3 Admin and Records 999555555 01-JAN-013 Admin and Records 999555555 01-JAN-01

1 Headquarters 999666666 19-JUN-811 Headquarters 999666666 19-JUN-81

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-22

CREATING A VIEW WITH ERRORSCREATING A VIEW WITH ERRORS

• If there are no syntax errors in a CREATE VIEW If there are no syntax errors in a CREATE VIEW statement, Oracle will create a view even if the statement, Oracle will create a view even if the view-defining query refers to a non-existent table view-defining query refers to a non-existent table or an invalid column of an existing table.or an invalid column of an existing table.

• The view will also be created even if the system The view will also be created even if the system user does not have privileges to access the tables user does not have privileges to access the tables which a view references.which a view references.

• The new view will be unusable and is categorized The new view will be unusable and is categorized as “created with errors.” as “created with errors.”

• In order to create such a view, the system user In order to create such a view, the system user must use the FORCE option of the CREATE must use the FORCE option of the CREATE VIEW command.VIEW command.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-23

CREATING A VIEW WITH ERRORSCREATING A VIEW WITH ERRORS

• In the CREATE VIEW command shown below, In the CREATE VIEW command shown below, the table named the table named divisionsdivisions does not exist and the does not exist and the view is created with errors. Oracle returns an view is created with errors. Oracle returns an appropriate warning message. appropriate warning message.

CREATE FORCE VIEW div_view AS CREATE FORCE VIEW div_view AS

SELECT * SELECT * FROM divisions;FROM divisions;Warning: View created with Warning: View created with

compilation errors.compilation errors.

• If we now create a table named divisions, a query If we now create a table named divisions, a query of the invalid div_view view will execute, and the of the invalid div_view view will execute, and the view is automatically recompiled and becomes view is automatically recompiled and becomes valid.valid.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-24

DROPPING VIEWDROPPING VIEW

• A DBA or view owner can drop a view with the A DBA or view owner can drop a view with the DROP VIEW command. The following DROP VIEW command. The following command drops a view named command drops a view named dept_viewdept_view..

DROP VIEW dept_view;DROP VIEW dept_view;

View dropped.View dropped.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-25

A Summary of VIEW Facts A Summary of VIEW Facts

• A view does not store data, but a view does A view does not store data, but a view does display data through a SELECT query as if the display data through a SELECT query as if the data were stored in the view.data were stored in the view.

• A view definition as provided by the CREATE A view definition as provided by the CREATE VIEW statement is stored in the database. VIEW statement is stored in the database. Further, Oracle develops what is termed an Further, Oracle develops what is termed an "execution plan" that is used to "gather up" the "execution plan" that is used to "gather up" the data that needs to be displayed by a view. This data that needs to be displayed by a view. This execution plan is also stored in the database.execution plan is also stored in the database.

• A view can simplify data presentation as well as A view can simplify data presentation as well as provide a kind of data security by limiting provide a kind of data security by limiting access to data based on a "need to know” basis. access to data based on a "need to know” basis.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-26

A Summary of VIEW Facts A Summary of VIEW Facts

• A view can display data from more than one table. A view can display data from more than one table. • Views can be used to update the underlying tables. Views can be used to update the underlying tables.

Views can also be limited to read-only access. Views can also be limited to read-only access.• Views can change the appearance of data. For Views can change the appearance of data. For

example, a view can be used to rename columns example, a view can be used to rename columns from tables without affecting the base table.from tables without affecting the base table.

• A view that has columns from more than one table A view that has columns from more than one table cannot be modified by an INSERT, DELETE, or cannot be modified by an INSERT, DELETE, or UPDATE command if a grouping function, UPDATE command if a grouping function, GROUP BY clause is part of the view definition.GROUP BY clause is part of the view definition.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-27

A Summary of VIEW Facts A Summary of VIEW Facts

• A view cannot reference the A view cannot reference the nextvalnextval and and currvalcurrval pseudocolumns created through the use of pseudocolumns created through the use of sequences.sequences.

• A row cannot be inserted in a view in which the A row cannot be inserted in a view in which the base table has a column with the NOT NULL or base table has a column with the NOT NULL or other constraint that cannot be satisfied by the new other constraint that cannot be satisfied by the new row data.row data.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-28

SYNONYMSSYNONYMS

• A A synonym synonym is an is an aliasalias, that is, a form of shorthand , that is, a form of shorthand used to simplify the task of referencing a database used to simplify the task of referencing a database object. object.

• Creating SynonymsCreating Synonyms• The general form of the CREATE SYNONYM The general form of the CREATE SYNONYM

command is:command is:

CREATE [PUBLIC] SYNONYM CREATE [PUBLIC] SYNONYM synonym_name FOR object_name;synonym_name FOR object_name;

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-29

SYNONYMSSYNONYMS

• There are two categories of synonyms, There are two categories of synonyms, publicpublic and and privateprivate..

• A public synonym can be accessed by any system A public synonym can be accessed by any system user.user.

• The individual creating a public synonym does not The individual creating a public synonym does not own the synonym – rather, it will belong to the own the synonym – rather, it will belong to the PUBLIC user group that exists within Oracle.PUBLIC user group that exists within Oracle.

• Private synonyms, on the other hand, belong to the Private synonyms, on the other hand, belong to the system user that creates them and reside in that system user that creates them and reside in that user's schema. user's schema.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-30

SYNONYMSSYNONYMS

• A system user can grant the privilege to use A system user can grant the privilege to use private synonyms that they own to other system private synonyms that they own to other system users.users.

• In order to create synonyms, you will need to have In order to create synonyms, you will need to have the CREATE SYNONYM privilege.the CREATE SYNONYM privilege.

• ““grant create synonym to tester;” grant create synonym to tester;” • This privilege will be granted to you by the DBA.This privilege will be granted to you by the DBA.• You must have the CREATE PUBLIC You must have the CREATE PUBLIC

SYNONYM privilege in order to create public SYNONYM privilege in order to create public synonyms.synonyms.

• ““grant create public synonym to tester;”grant create public synonym to tester;”

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-31

SYNONYMSSYNONYMS• The three advantages to synonym usage. The three advantages to synonym usage.

          First, a synonym provides what is termed First, a synonym provides what is termed location location transparencytransparency because the synonym because the synonym name hides the name hides the actual object name and actual object name and object object owner from the owner from the user of the synonym. user of the synonym.

          Second, you can create a synonym for a database Second, you can create a synonym for a database object and then refer to the synonym in object and then refer to the synonym in

application code. The underlying object can be application code. The underlying object can be moved or renamed, and a redefinition of the moved or renamed, and a redefinition of the synonym synonym will allow the application code to will allow the application code to continue to continue to execute without errors. execute without errors.

          Third, a public synonym can be used to allow easy Third, a public synonym can be used to allow easy access to an object for all system users. access to an object for all system users.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-32

Dropping SynonymsDropping Synonyms

• If you own a synonym, you have the right to drop If you own a synonym, you have the right to drop (delete) the synonym. The DROP SYNONYM (delete) the synonym. The DROP SYNONYM command is quite simple.command is quite simple.

DROP SYNONYM synonym_name;DROP SYNONYM synonym_name;

• In order to drop a public synonym you must In order to drop a public synonym you must include the PUBLIC keyword in the DROP include the PUBLIC keyword in the DROP SYNONYM command. SYNONYM command.

• In order to drop a public synonym, you must have In order to drop a public synonym, you must have the DROP PUBLIC SYNONYM privilege. the DROP PUBLIC SYNONYM privilege. DROP PUBLIC SYNONYM DROP PUBLIC SYNONYM synonym_name;synonym_name;

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-33

Renaming SynonymsRenaming Synonyms

• Private synonyms can be renamed with the Private synonyms can be renamed with the RENAME SYNONYM command.RENAME SYNONYM command.

• All existing references to the synonym are All existing references to the synonym are automatically updated.automatically updated.

• Any system user with privileges to use a synonym Any system user with privileges to use a synonym will retain those privileges if the synonym name is will retain those privileges if the synonym name is changed. changed.

• The syntax of the RENAME SYNONYM command The syntax of the RENAME SYNONYM command is like that for the RENAME command for any other is like that for the RENAME command for any other database object such as a view or table. database object such as a view or table. RENAME old_synonym_name TO RENAME old_synonym_name TO

new_synonym_name;new_synonym_name;

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-34

Renaming SynonymsRenaming Synonyms

• The RENAME SYNONYM command only The RENAME SYNONYM command only works for private synonyms.works for private synonyms.

• If we attempt to rename a public synonym If we attempt to rename a public synonym such as the such as the tblspacestblspaces synonym, Oracle will synonym, Oracle will return an ORA-04043: return an ORA-04043: object tblspaces object tblspaces does not existdoes not exist error message as is shown error message as is shown here.here.

RENAME tblspaces TO ts;RENAME tblspaces TO ts;

ORA-04043: object ORA-04043: object TBLSPACES TBLSPACES does not existdoes not exist

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-35

SEQUENCES SEQUENCES

• Oracle provides the capability to generate Oracle provides the capability to generate sequences of unique numbers, and they are called sequences of unique numbers, and they are called sequences. sequences.

• Just like tables, views, indexes, and synonyms, a Just like tables, views, indexes, and synonyms, a sequence is a type of database object. sequence is a type of database object.

• Sequences are used to generate unique, sequential Sequences are used to generate unique, sequential integer values that are used as primary key values integer values that are used as primary key values in database tables.in database tables.

• The sequence of numbers can be generated in either The sequence of numbers can be generated in either ascending or descending order. ascending or descending order.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-36

Creating SequencesCreating Sequences

• The syntax of the CREATE SEQUENCE command The syntax of the CREATE SEQUENCE command is fairly complex because it has numerous optional is fairly complex because it has numerous optional clauses.clauses.

CREATE SEQUENCE <sequence name>CREATE SEQUENCE <sequence name>[INCREMENT BY <number>][INCREMENT BY <number>][START WITH <start value number>][START WITH <start value number>][MAXVALUE <MAXIMUM VLAUE NUMBER>][MAXVALUE <MAXIMUM VLAUE NUMBER>][NOMAXVALUE][NOMAXVALUE][MINVALUE <minimum value number>][MINVALUE <minimum value number>][CYCLE][CYCLE][NOCYCLE][NOCYCLE][CACHE <number of sequence value to cache>][CACHE <number of sequence value to cache>][NOCACHE][NOCACHE][ORDER][ORDER][NOORDER];[NOORDER];

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-37

ExampleExample

CREATE SEQUENCE order_number_sequenceCREATE SEQUENCE order_number_sequence

INCREMENT BY 1INCREMENT BY 1

START WITH 1START WITH 1

MAXVALUE 100000000MAXVALUE 100000000

MINVALUE 1MINVALUE 1

CYCLECYCLE

CACHE 10;CACHE 10;

Sequence created.Sequence created.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-38

Accessing Sequence Values Accessing Sequence Values • Sequence values are generated through the use of two Sequence values are generated through the use of two

pseudocolumnspseudocolumns named named currvalcurrval and and nextvalnextval. . • A pseudocolumn behaves like a table column, but A pseudocolumn behaves like a table column, but

psuedocolumns are not actually stored in a table. psuedocolumns are not actually stored in a table. • We can select values from pseudocolumns but cannot We can select values from pseudocolumns but cannot

perform manipulations on their values.perform manipulations on their values.• The first time you select the The first time you select the nextvalnextval pseudocolumn, pseudocolumn,

the initial value in the sequence is returned.the initial value in the sequence is returned.• Subsequent selections of the Subsequent selections of the nextvalnextval pseudocolumn pseudocolumn

will cause the sequence to increment as specified by will cause the sequence to increment as specified by the INCREMENT BY clause and will return the the INCREMENT BY clause and will return the newly generated sequence value. newly generated sequence value.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-39

Accessing Sequence Values Accessing Sequence Values

• The The currvalcurrval pseudocolumn returns the current value pseudocolumn returns the current value of the sequence, which is the value returned by the of the sequence, which is the value returned by the last reference to nextval. last reference to nextval.

• ExampleExample

CREATE TABLE sales_order (CREATE TABLE sales_order ( order_number NUMBER(9)order_number NUMBER(9)

CONSTRAINT pk_sales_order PRIMARY KEY,CONSTRAINT pk_sales_order PRIMARY KEY, order_amount NUMBER(9,2));order_amount NUMBER(9,2));

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-40

Accessing Sequence Values Accessing Sequence Values

• The INSERT commands shown below insert three rows The INSERT commands shown below insert three rows into the into the sales_ordersales_order table. The INSERT commands table. The INSERT commands reference the reference the order_number_sequence.nextvalorder_number_sequence.nextval pseudocolumn. pseudocolumn. INSERT INTO sales_order INSERT INTO sales_order

VALUES(order_number_sequence.nextval, VALUES(order_number_sequence.nextval, 155.59 );155.59 );INSERT INTO sales_order INSERT INTO sales_order

VALUES(order_number_sequence.nextval, VALUES(order_number_sequence.nextval, 450.00 );450.00 );INSERT INTO sales_orderINSERT INTO sales_orderVALUES(order_number_sequence.nextval, VALUES(order_number_sequence.nextval,

16.95);16.95);

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-41

Accessing Sequence Values Accessing Sequence Values

SELECT *SELECT *

FROM sales_order;FROM sales_order;

  

ORDER_NUMBER ORDER_AMOUNTORDER_NUMBER ORDER_AMOUNT

------------ ------------------------ ------------

1 155.591 155.59

2 4502 450

3 16.953 16.95

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-42

Accessing Sequence Values Accessing Sequence Values

• Use of Use of currval.currval.

CREATE TABLE order_details (CREATE TABLE order_details (

order_numberorder_number NUMBER(9),NUMBER(9),

order_roworder_row NUMBER(3),NUMBER(3),

product_descproduct_desc VARCHAR2(15),VARCHAR2(15),

quantity_orderedquantity_ordered NUMBER(3),NUMBER(3),

product_priceproduct_price NUMBER(9,2),NUMBER(9,2),

CONSTRAINT pk_order_details CONSTRAINT pk_order_details

PRIMARY KEY (order_number, order_row),PRIMARY KEY (order_number, order_row),

CONSTRAINT fk_order_number FOREIGN KEY CONSTRAINT fk_order_number FOREIGN KEY (order_number) REFERENCES sales_order);(order_number) REFERENCES sales_order);

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-43

Accessing Sequence Values Accessing Sequence Values

• The order_details table has a FOREIGN KEY The order_details table has a FOREIGN KEY reference to the sales_order table through the reference to the sales_order table through the order_number column.order_number column.

DELETE FROM sales_order;DELETE FROM sales_order;INSERT INTO sales_order INSERT INTO sales_order VALUES ( order_number_sequence.nextval, 200.00 );VALUES ( order_number_sequence.nextval, 200.00 );INSERT INTO order_detailsINSERT INTO order_details VALUES ( order_number_sequence.currval, 1, 'End VALUES ( order_number_sequence.currval, 1, 'End

Table',1, 100.00);Table',1, 100.00);INSERT INTO order_detailsINSERT INTO order_details VALUES ( order_number_sequence.currval, 2, 'Table VALUES ( order_number_sequence.currval, 2, 'Table

Lamp',2, 50.00);Lamp',2, 50.00);

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-44

Accessing Sequence Values Accessing Sequence Values

SELECT * SELECT *

FROM sales_order;FROM sales_order;

  

ORDER_NUMBER ORDER_AMOUNTORDER_NUMBER ORDER_AMOUNT

------------ ------------------------ ------------

5 2005 200

  

SELECT * SELECT *

FROM order_details;FROM order_details;

  ORDER_NUMBER ORDER_ROW PRODUCT_DESC QUANTITY_ORDERED PRODUCT_PRICEORDER_NUMBER ORDER_ROW PRODUCT_DESC QUANTITY_ORDERED PRODUCT_PRICE

--------- -------- ---------- ------------- ---------- --------- -------- ---------- ------------- ---------- 5 1 End Table 1 5 1 End Table 1 100 100

5 2 Table Lamp 2 505 2 Table Lamp 2 50

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-45

Altering a SequenceAltering a Sequence

• A sequence is usually altered when it is desirable A sequence is usually altered when it is desirable to set or eliminate the values of the MINVALUE to set or eliminate the values of the MINVALUE or MAXVALUE parameters, or to change the or MAXVALUE parameters, or to change the INCREMENT BY value, or to change the number INCREMENT BY value, or to change the number of cached sequence numbers. of cached sequence numbers.

• The ALTER SEQUENCE command shown here The ALTER SEQUENCE command shown here changes the MAXVALUE of the changes the MAXVALUE of the order_number_sequence to 200,000,000.order_number_sequence to 200,000,000.

ALTER SEQUENCE order_number_sequence ALTER SEQUENCE order_number_sequence MAXVALUE 200000000;MAXVALUE 200000000;Sequence altered.Sequence altered.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-46

Altering a SequenceAltering a Sequence

• When specifying a MINVALUE clause, the When specifying a MINVALUE clause, the specified value should be less than the specified value should be less than the MAXVALUE where a sequence generates MAXVALUE where a sequence generates ascending numbers.ascending numbers.

• In the case of a descending sequence, the In the case of a descending sequence, the MAXVALUE should be less than the MAXVALUE should be less than the MINVALUE. MINVALUE.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-47

Viewing Sequence PropertiesViewing Sequence Properties

• You may need to review the names and properties of You may need to review the names and properties of your sequences.your sequences.

• You can do this by querying the USER_SEQUENCES You can do this by querying the USER_SEQUENCES system view with a SELECT command. This view is part system view with a SELECT command. This view is part of the database's data dictionary.of the database's data dictionary.

SELECT * FROM USER_SEQUENCES;SELECT * FROM USER_SEQUENCES;

  SEQUENCE_NAME MIN_VAL MAX_VALUE INCRE C O CACHE_SIZE Last_NSEQUENCE_NAME MIN_VAL MAX_VALUE INCRE C O CACHE_SIZE Last_N

---------------- ------ ---------- ----- -- -- -------------------- ------ ---------- ----- -- -- -------- ---- ----------

ORDER_NUMBER_SEQUENCEORDER_NUMBER_SEQUENCE 1 200000000 1 Y N 10 6 1 200000000 1 Y N 10 6

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-48

Dropping a SequenceDropping a Sequence• DROP SEQUENCE command is used to drop DROP SEQUENCE command is used to drop

sequences that need to be recreated or are no longer sequences that need to be recreated or are no longer needed. needed.

• The general format is shown here along with an The general format is shown here along with an example that drops the example that drops the order_number_sequenceorder_number_sequence object.object.

DROP SEQUENCE <sequence name>;DROP SEQUENCE <sequence name>;

   DROP SEQUENCE order_number_sequence;DROP SEQUENCE order_number_sequence;

Sequence dropped.Sequence dropped.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-49

CHAPTER 9: CHAPTER 9: SQL*PLUS REPORTSSQL*PLUS REPORTS

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-50

An SQL*Plus PROGRAM COMMAND An SQL*Plus PROGRAM COMMAND FileFile

• Interactive commands can be used to specify report Interactive commands can be used to specify report headings, report footers, report titles, page headings, report footers, report titles, page numbers, and other common report features that numbers, and other common report features that managers tend to request.managers tend to request.

• Unfortunately, if you exit SQL*Plus, all of the Unfortunately, if you exit SQL*Plus, all of the information about a report's features is lost unless information about a report's features is lost unless you save your commands in a file.you save your commands in a file.

• For this reason, we will also focus on creating files For this reason, we will also focus on creating files that will store SQL*Plus commands. We'll refer to that will store SQL*Plus commands. We'll refer to this type of file as an SQL*Plus program command this type of file as an SQL*Plus program command file, or simply an SQL program. The filename file, or simply an SQL program. The filename extension used for these files is extension used for these files is .sql.sql. .

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-51

ExampleExample

• The following program gives a sample SQL*Plus The following program gives a sample SQL*Plus program command file.program command file.

• This SQL program will produce the report shown in This SQL program will produce the report shown in Figures 9.1a and 9.1b. All of the data for the report Figures 9.1a and 9.1b. All of the data for the report are selected from the are selected from the assignmentassignment table of the table of the Company database. Company database.

• The SQL program has numerous commands. The SQL program has numerous commands.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-52

ExampleExample

REM Program: ch9-1.sqlREM Program: ch9-1.sqlREM Programmer: dbock; 3-20-2003REM Programmer: dbock; 3-20-2003REM Description: A program to list employee work REM Description: A program to list employee work

history history REM on projects.REM on projects.  TTITLE 'Project Information' TTITLE 'Project Information' BTITLE SKIP 1 CENTER 'Not for external dissemination.' BTITLE SKIP 1 CENTER 'Not for external dissemination.' REPHEADER 'Project Report #1 –- prepared by D. Bock' REPHEADER 'Project Report #1 –- prepared by D. Bock'

SKIP 2SKIP 2REPFOOTER SKIP 3 '-- Last Page of Report --'REPFOOTER SKIP 3 '-- Last Page of Report --'  SET LINESIZE 55SET LINESIZE 55SET PAGESIZE 24SET PAGESIZE 24SET NEWPAGE 1SET NEWPAGE 1  

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-53

Example Cont’dExample Cont’d

COLUMN "Emp. Soc. Sec. #" FORMAT A16COLUMN "Emp. Soc. Sec. #" FORMAT A16COLUMN "Hours Worked" FORMAT 999.99COLUMN "Hours Worked" FORMAT 999.99SELECT work_emp_ssn "Emp. Soc. Sec. #",SELECT work_emp_ssn "Emp. Soc. Sec. #", work_pro_number "Project #", work_hours "Hours work_pro_number "Project #", work_hours "Hours

Worked"Worked"FROM assignmentFROM assignmentORDER BY work_emp_ssn, work_pro_number;ORDER BY work_emp_ssn, work_pro_number;

• The report produced is shown next.The report produced is shown next.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-54

Sun Apr 14 page 1Sun Apr 14 page 1 Project InformationProject Information  Project Report #1 - prepared by D. BockProject Report #1 - prepared by D. Bock  Emp. Soc. Sec. # Project # Hours WorkedEmp. Soc. Sec. # Project # Hours Worked---------------- ---------- ---------------------------- ---------- ------------999111111 1 31.40999111111 1 31.40999111111 2 8.50999111111 2 8.50999222222 10 34.50999222222 10 34.50999222222 30 5.10999222222 30 5.10999333333 3 42.10999333333 3 42.10999444444 1999444444 1999444444 2 12.20999444444 2 12.20999444444 3 10.50999444444 3 10.50999444444 10 10.10999444444 10 10.10999444444 20 11.80999444444 20 11.80999555555 20 14.80999555555 20 14.80999555555 30 19.20999555555 30 19.20999666666 20999666666 20999887777 10 10.20999887777 10 10.20   Not for external dissemination.Not for external dissemination.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-55

Sun Apr 14 page 2Sun Apr 14 page 2 Project InformationProject Information  Emp. Soc. Sec. # Project # Hours WorkedEmp. Soc. Sec. # Project # Hours Worked---------------- ---------- ---------------------------- ---------- ------------999887777 30 30.80999887777 30 30.80999888888 1 21.00999888888 1 21.00999888888 2 22.00999888888 2 22.00      -- Last Page of Report ---- Last Page of Report --               Not for external dissemination.Not for external dissemination.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-56

RemarksRemarks

• Optional remarks are typically entered at the Optional remarks are typically entered at the beginning of a command file program that identify beginning of a command file program that identify the filename, programmer name, and date of the filename, programmer name, and date of program creation. program creation.

• A brief description of the program is also provided. A brief description of the program is also provided. You may also list modifications made by You may also list modifications made by programmer name, date, and description here.programmer name, date, and description here.

• Remarks and blank lines are used throughout a Remarks and blank lines are used throughout a program to enhance the understandability and program to enhance the understandability and readability of programming code.readability of programming code.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-57

Top and Bottom TitlesTop and Bottom Titles

• Titles and footers on reports enhance the meaning Titles and footers on reports enhance the meaning of reports for managerial system users. of reports for managerial system users.

• Reports are rarely disseminated to managers Reports are rarely disseminated to managers without appropriate title and footers.without appropriate title and footers.

• SQL*Plus supports the programming of four types SQL*Plus supports the programming of four types of titles and footers:of titles and footers:

1.1. Top title,Top title,2.2. Bottom title,Bottom title,3.3. Report header andReport header and4.4. Report footer. Report footer.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-58

Top and Bottom TitlesTop and Bottom Titles

• The TTITLE command (short for top title) prints a The TTITLE command (short for top title) prints a title on title on each pageeach page of a report. of a report.

• When a simple TTITLE command like the one When a simple TTITLE command like the one shown below is used, the report will automatically shown below is used, the report will automatically display the report date and page number. display the report date and page number.

TTITLE 'Project Information'TTITLE 'Project Information'

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-59

Top and Bottom TitlesTop and Bottom Titles

• You can also issue the TTITLE command You can also issue the TTITLE command interactively at the SQL> prompt. interactively at the SQL> prompt.

• The first TTITLE command shown below will turn The first TTITLE command shown below will turn the report title off. the report title off.

• The second one will change the report title The second one will change the report title interactively when followed by a slash (/) interactively when followed by a slash (/) command. command.

TTITLE OFFTTITLE OFFTTITLE 'Project and Employee TTITLE 'Project and Employee Information'Information'//

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-60

Top and Bottom TitlesTop and Bottom Titles

• The BTITLE command prints a bottom title with The BTITLE command prints a bottom title with the specified information at the bottom of the specified information at the bottom of each each pagepage of a report. of a report.

• For example, your organization may want each For example, your organization may want each page of a report marked as not for external page of a report marked as not for external dissemination as is shown in the BTITLE command dissemination as is shown in the BTITLE command here.here.

BTITLE SKIP 1 CENTER 'Not for external BTITLE SKIP 1 CENTER 'Not for external dissemination.' dissemination.'

  

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-61

Top and Bottom TitlesTop and Bottom Titles

• The SKIP clause is optional. The SKIP clause is optional. • SKIP 1 will insert one blank line into the report.SKIP 1 will insert one blank line into the report.• You can specify the number of lines to skip. If the You can specify the number of lines to skip. If the

SKIP option is specified prior to the bottom title, as SKIP option is specified prior to the bottom title, as is done above, then one line is skipped prior to is done above, then one line is skipped prior to printing the bottom title.printing the bottom title.

• The CENTER option centers the bottom title The CENTER option centers the bottom title output. output.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-62

Top and Bottom TitlesTop and Bottom Titles

• In addition to CENTER, you can also use the In addition to CENTER, you can also use the keywords RIGHT and LEFT within both the keywords RIGHT and LEFT within both the TTITLE and BTITLE commands to control the TTITLE and BTITLE commands to control the display of report information. display of report information.

• An example multi-lined TTITLE command is An example multi-lined TTITLE command is shown below. shown below.

TTITLE LEFT date_var –TTITLE LEFT date_var – RIGHT 'Page: ' FORMAT 99 sql.pno SKIP 1 -RIGHT 'Page: ' FORMAT 99 sql.pno SKIP 1 - CENTER 'Project and Employee Information'CENTER 'Project and Employee Information'

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-63

Top and Bottom TitlesTop and Bottom Titles

• A dash ( - ) at the end of a line continues the A dash ( - ) at the end of a line continues the TTITLE command.TTITLE command.

• The The date_vardate_var entry is a variable name that stores entry is a variable name that stores the date.the date.

• When a complex TTITLE command is used, Oracle When a complex TTITLE command is used, Oracle does not automatically print the date and page does not automatically print the date and page number information as was done earliernumber information as was done earlier . .

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-64

Report Headers and FootersReport Headers and Footers

• A report header can be used to add meaningful A report header can be used to add meaningful information to the top of the information to the top of the first pagefirst page of a report. of a report.

• You should use the REPHEADER command You should use the REPHEADER command whenever you want information to be displayed on whenever you want information to be displayed on only the first page.only the first page.

• The REPHEADER command shown below uses the The REPHEADER command shown below uses the SKIP 2 option to insert two blank lines immediately SKIP 2 option to insert two blank lines immediately after the report header is printed. You'll also notice after the report header is printed. You'll also notice that the report header prints after the top title line.that the report header prints after the top title line.

REPHEADER 'Project Report #1 -- prepared by REPHEADER 'Project Report #1 -- prepared by D. Bock' SKIP 2D. Bock' SKIP 2

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-65

Report Headers and FootersReport Headers and Footers

• Report footers add meaningful information to the Report footers add meaningful information to the bottom of the bottom of the last pagelast page of a report. of a report.

• In the command shown here, the SKIP 3 option In the command shown here, the SKIP 3 option provides for three skipped blank lines prior to provides for three skipped blank lines prior to printing the report footer.printing the report footer.

• You will also note that the report footer prints prior You will also note that the report footer prints prior to the bottom title line. to the bottom title line. REPFOOTER SKIP 3 '-- Last Page of Report --'REPFOOTER SKIP 3 '-- Last Page of Report --'

• The OFF option also applies to report headers and The OFF option also applies to report headers and footers, and will turn the report header and/or footer footers, and will turn the report header and/or footer off.off.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-66

Setting the Line and Page SizeSetting the Line and Page Size

• The SET LINESIZE command specifies the size of The SET LINESIZE command specifies the size of an output line in characters.an output line in characters.

• The example report shown before has a line size of The example report shown before has a line size of 55 characters.55 characters.

SET LINESIZE 55SET LINESIZE 55

• Similarly, the SET PAGESIZE command specifies Similarly, the SET PAGESIZE command specifies the number of lines to be printed per page. the number of lines to be printed per page.

• A typical setting is 50 to 55 lines of output per page A typical setting is 50 to 55 lines of output per page for 10-point or 12-point printer fonts.for 10-point or 12-point printer fonts.

• The command shown below sets the page size to 50 The command shown below sets the page size to 50 lines.lines.

SET PAGESIZE 50SET PAGESIZE 50

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-67

Setting the Line and Page SizeSetting the Line and Page Size

• The SET NEWPAGE command specifies the The SET NEWPAGE command specifies the number of blank lines to print before the top title number of blank lines to print before the top title line of a report, that is, the line that displays the line of a report, that is, the line that displays the report date and page number. report date and page number.

• This is useful for aligning reports produced by This is useful for aligning reports produced by various types of printers. various types of printers.

• The SET NEWPAGE command does not affect the The SET NEWPAGE command does not affect the PAGESIZE value.PAGESIZE value.

• The command shown below specifies 6 blank lines The command shown below specifies 6 blank lines at the top of at the top of each pageeach page. If the page size is set to 55, . If the page size is set to 55, this will leave 49 lines for displaying output.this will leave 49 lines for displaying output.

SET NEWPAGE 6SET NEWPAGE 6

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-68

Output to the Computer Monitor ScreenOutput to the Computer Monitor Screen

• When you are testing an SQL program that will be When you are testing an SQL program that will be used to produce a printed report, it is sometimes used to produce a printed report, it is sometimes useful to specify values for the LINESIZE, useful to specify values for the LINESIZE, PAGESIZE, and NEWPAGE values so that report PAGESIZE, and NEWPAGE values so that report output will fit on a computer monitor screen.output will fit on a computer monitor screen.

• Typical values for screen output are shown below.Typical values for screen output are shown below.

SET LINESIZE 79SET LINESIZE 79SET PAGESIZE 24SET PAGESIZE 24SET NEWPAGE 0SET NEWPAGE 0

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-69

Output to the Computer Monitor ScreenOutput to the Computer Monitor Screen

• You will probably want the computer monitor You will probably want the computer monitor screen output to pause between pages so that you screen output to pause between pages so that you can review the report.can review the report.

• This can be accomplished by the SET PAUSE This can be accomplished by the SET PAUSE commands shown below. commands shown below.

SET PAUSE 'More . . .'SET PAUSE 'More . . .'SET PAUSE ONSET PAUSE ONSET PAUSE OFFSET PAUSE OFF

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-70

CONTROL BREAK REPORTSCONTROL BREAK REPORTS

• A control break report organizes information into A control break report organizes information into meaningful groups. meaningful groups.

• We will organize the new report into groups We will organize the new report into groups according to each employee's social security according to each employee's social security number. The modified example program is listed number. The modified example program is listed below.below.

• The additional lines of code required to produce the The additional lines of code required to produce the control break report are highlighted in bold text.control break report are highlighted in bold text.

• Additionally, the decision was made to remove the Additionally, the decision was made to remove the report header and report footer. report header and report footer.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-71

Example ModifiedExample Modified

REM Program: ch9-2.sqlREM Program: ch9-2.sqlREM Programmer: dbock; 3-20-2003REM Programmer: dbock; 3-20-2003REM Description: A sample program control break REM Description: A sample program control break

report.report.  TTITLE 'Project Information' TTITLE 'Project Information' BTITLE SKIP 1 CENTER 'Not for external dissemination.' BTITLE SKIP 1 CENTER 'Not for external dissemination.'   SET LINESIZE 55SET LINESIZE 55SET PAGESIZE 24SET PAGESIZE 24SET NEWPAGE 1SET NEWPAGE 1  COLUMN "Emp. Soc. Sec. #" FORMAT A16COLUMN "Emp. Soc. Sec. #" FORMAT A16COLUMN "Hours Worked" FORMAT 999.99COLUMN "Hours Worked" FORMAT 999.99

SPOOL report9-2.1st SPOOL report9-2.1st

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-72

Example Cont’dExample Cont’d

CLEAR BREAKSCLEAR BREAKSBREAK ON "Emp. Soc. Sec. #" SKIP 2 ON REPORTBREAK ON "Emp. Soc. Sec. #" SKIP 2 ON REPORTCOMPUTE SUM OF "Hours Worked" ON "Emp. Soc. Sec. #“COMPUTE SUM OF "Hours Worked" ON "Emp. Soc. Sec. #“COMPUTE SUM OF "Hours Worked" ON REPORT SPOOL report9-COMPUTE SUM OF "Hours Worked" ON REPORT SPOOL report9-

2.lst2.lst  SELECT work_emp_ssn "Emp. Soc. Sec. #",SELECT work_emp_ssn "Emp. Soc. Sec. #", work_pro_number "Project #", work_hours "Hourswork_pro_number "Project #", work_hours "Hours Worked"Worked"FROM assignmentFROM assignmentORDER BY work_emp_ssn, work_pro_number;ORDER BY work_emp_ssn, work_pro_number;  SPOOL OFFSPOOL OFF

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-73

Sun Apr 14 page 1Sun Apr 14 page 1 Project InformationProject Information  Project Report #1 - prepared by D. BockProject Report #1 - prepared by D. Bock  Emp. Soc. Sec. # Project # Hours WorkedEmp. Soc. Sec. # Project # Hours Worked---------------- ---------- ---------------------------- ---------- ------------999111111 1 31.40999111111 1 31.40 2 8.502 8.50**************** ------------**************** ------------sum 39.90sum 39.90

999222222 10 34.50999222222 10 34.50 30 5.1030 5.10**************** ------------**************** ------------sum 39.60sum 39.60

999333333 3 42.10999333333 3 42.10**************** ------------**************** ------------

Not for external dissemination.Not for external dissemination.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-74

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-75

The BREAK CommandThe BREAK Command• The BREAK command groups data rows for a The BREAK command groups data rows for a

control break report. The syntax of the BREAK control break report. The syntax of the BREAK command is:command is:

BREAK ON (expression1, ON expression2, BREAK ON (expression1, ON expression2, …… \row\page\ \row\page\report) report) ……

[SKIP n | [SKIP] PAGE][SKIP n | [SKIP] PAGE][NODUPLICATES | DUPLICATES];[NODUPLICATES | DUPLICATES];

• The BREAK command can be used to break on an The BREAK command can be used to break on an expression, row, page, report, or more than one of expression, row, page, report, or more than one of these at a time. The BREAK command used in these at a time. The BREAK command used in example program is shown below. example program is shown below.

CLEAR BREAKSCLEAR BREAKS

BREAK ON "Emp. Soc. Sec. #" SKIP 2 ON REPORTBREAK ON "Emp. Soc. Sec. #" SKIP 2 ON REPORT

• The CLEAR BREAKS command clears any The CLEAR BREAKS command clears any previously established breaks.previously established breaks.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-76

Output StyleOutput Style• The style of output shown in the example report is The style of output shown in the example report is

called NONDUPLICATES, or NODUP because each called NONDUPLICATES, or NODUP because each group value (employee social security number) is group value (employee social security number) is shown only once.shown only once.

• This is the default BREAK output method so there is This is the default BREAK output method so there is no need to specify it. While this form of output no need to specify it. While this form of output diverges from the relational, two-dimensional, matrix diverges from the relational, two-dimensional, matrix format, it is much easier for managers to read.format, it is much easier for managers to read.

• The NODUP default can be overwritten by specifying The NODUP default can be overwritten by specifying the keyword DUP with the BREAK command as is the keyword DUP with the BREAK command as is shown here. This will yield the purely relational, two-shown here. This will yield the purely relational, two-dimensional, matrix format for output.dimensional, matrix format for output.

BREAK ON "Emp. Soc. Sec. #" DUP SKIP 2BREAK ON "Emp. Soc. Sec. #" DUP SKIP 2

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-77

SKIP and PAGE KeywordsSKIP and PAGE Keywords

• To enhance the readability of a report, one or more To enhance the readability of a report, one or more blank rows can be inserted after each social blank rows can be inserted after each social security number grouping. As we noted earlier, the security number grouping. As we noted earlier, the SKIP keyword inserts the blank rows. Our program SKIP keyword inserts the blank rows. Our program specified to skip two lines prior to beginning the specified to skip two lines prior to beginning the next report group. next report group.

• Replacing the keyword SKIP with PAGE will Replacing the keyword SKIP with PAGE will cause a cause a page ejectpage eject to occur after each grouping. to occur after each grouping.

• This will produce a report with each social security This will produce a report with each social security number beginning on a new page. This will also number beginning on a new page. This will also cause each group to be preceded by new column cause each group to be preceded by new column headings. headings.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-78

The COMPUTE CommandThe COMPUTE Command

• In order for a COMPUTE command to compute In order for a COMPUTE command to compute subtotals and totals properly it must be used in subtotals and totals properly it must be used in conjunction with a BREAK command.conjunction with a BREAK command.

• If you have not specified a BREAK command, If you have not specified a BREAK command, then a COMPUTE command will not produce any then a COMPUTE command will not produce any results!results!

• When used with BREAK, a COMPUTE command When used with BREAK, a COMPUTE command displays values that are computed for the BREAK displays values that are computed for the BREAK expression. The syntax of the COMPUTE expression. The syntax of the COMPUTE command is shown here. command is shown here.

COMPUTE {group function} OF {column_name | COMPUTE {group function} OF {column_name | column_name_alias,. . .} ON {break_column_name | ROW | PAGE | column_name_alias,. . .} ON {break_column_name | ROW | PAGE |

REPORT};REPORT};

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-79

The SPOOL CommandThe SPOOL Command

• The SPOOL command routes the output from a The SPOOL command routes the output from a SQL*Plus program to the specified filename. SQL*Plus program to the specified filename.

• The SPOOL command shown below routes output The SPOOL command shown below routes output to a file named to a file named report9-2.lstreport9-2.lst..

• The "lst" filename extension is short for listing; The "lst" filename extension is short for listing; however, you can specify any filename extension however, you can specify any filename extension that you desire.that you desire.

• The SPOOL OFF command terminates writing to The SPOOL OFF command terminates writing to the output file.the output file.

SPOOL report9-2.lstSPOOL report9-2.lstSPOOL OFFSPOOL OFF

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-80

Additional BREAK Command DetailsAdditional BREAK Command Details

• The BREAK command in the example program specifies a The BREAK command in the example program specifies a break on a column as well as on a report. You can also break break on a column as well as on a report. You can also break on any kind of expression, on rows, and on pages.on any kind of expression, on rows, and on pages.

• The BREAK ON ROW command can be used to change report The BREAK ON ROW command can be used to change report spacing. The BREAK command shown below will insert a spacing. The BREAK command shown below will insert a blank line between each row of the blank line between each row of the assignmentassignment report. report.

BREAK ON ROW SKIP 1BREAK ON ROW SKIP 1

• A column break and a row break can be used together. In A column break and a row break can be used together. In conjunction, these two breaks create a double-spaced report conjunction, these two breaks create a double-spaced report that is still separated by column values. The command shown that is still separated by column values. The command shown here will produce a double-spaced report that also breaks at the here will produce a double-spaced report that also breaks at the end of the report. end of the report.

BREAK ON "Emp. Soc. Sec. #" SKIP 1 ON REPORT ON ROW SKIP 1BREAK ON "Emp. Soc. Sec. #" SKIP 1 ON REPORT ON ROW SKIP 1

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-81

Viewing Current BREAK and COMPUTE Viewing Current BREAK and COMPUTE Command SettingsCommand Settings

• Only one BREAK command can be active at a time.Only one BREAK command can be active at a time.• You can interactively replace the current BREAK You can interactively replace the current BREAK

command by typing a new command at the SQL> prompt.command by typing a new command at the SQL> prompt.• If you forget which BREAK command is active, simply If you forget which BREAK command is active, simply

type the command BREAK on a line by itself and type the command BREAK on a line by itself and SQL*Plus will display the break status.SQL*Plus will display the break status.

• Note that the default for the BREAK command is no Note that the default for the BREAK command is no duplicates (NODUP).duplicates (NODUP).

BREAKBREAKbreak on report nodupbreak on report nodup on Emp. Soc. Sec. # skip 2 nodupon Emp. Soc. Sec. # skip 2 nodup

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-82

Viewing Current BREAK and COMPUTE Viewing Current BREAK and COMPUTE Command SettingsCommand Settings

• Unlike BREAK, the COMPUTE command is cumulative. Unlike BREAK, the COMPUTE command is cumulative. • While you are testing a program, you may accumulate quite a While you are testing a program, you may accumulate quite a

number of COMPUTE settings. You can display the current number of COMPUTE settings. You can display the current settings by simply typing the COMPUTE command at the SQL> settings by simply typing the COMPUTE command at the SQL> prompt.prompt.

COMPUTECOMPUTECOMPUTE sum LABEL 'sum' OF Hours Worked ON Emp. Soc. Sec. #COMPUTE sum LABEL 'sum' OF Hours Worked ON Emp. Soc. Sec. #COMPUTE sum LABEL 'sum' OF Hours Worked ON REPORTCOMPUTE sum LABEL 'sum' OF Hours Worked ON REPORT

• You can clear COMPUTE settings by typing CLEAR COMPUTE You can clear COMPUTE settings by typing CLEAR COMPUTE at the SQL> prompt or by placing the command within a at the SQL> prompt or by placing the command within a program.program.

• When the command is used interactively, Oracle will respond as When the command is used interactively, Oracle will respond as shown below.shown below.

CLEAR COMPUTECLEAR COMPUTEcomputes clearedcomputes cleared

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-83

CREATING MASTER-DETAIL CREATING MASTER-DETAIL REPORTSREPORTS

• A master-detail report is a form of control break report A master-detail report is a form of control break report because the report presents information that is "grouped.“because the report presents information that is "grouped.“

• The report typically displays data rows from more than The report typically displays data rows from more than one table.one table.

• Consider the one-to-many relationship between the Consider the one-to-many relationship between the departmentdepartment and and projectproject tables for the Company as tables for the Company as described in Appendix A.described in Appendix A.

• Each department controls numerous projects, and a project Each department controls numerous projects, and a project belongs to a single department.belongs to a single department.

• In this situation, the rows in the In this situation, the rows in the departmentdepartment table are table are "master" rows because the "master" rows because the departmentdepartment table is on the "one" table is on the "one" side of the one-to-many relationship.side of the one-to-many relationship.

• The associated The associated projectproject table rows provide the "detail" table rows provide the "detail" information. information.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-84

• ExampleExample• Program Program ch9-3.sqlch9-3.sql will produce the master-detail report for the will produce the master-detail report for the

department-projectdepartment-project relationship. relationship.

REM Program: ch9-3.sqlREM Program: ch9-3.sqlREM Programmer: dbock; Date: 3-20-2003REM Programmer: dbock; Date: 3-20-2003REM Description: A sample Master-Detail reportREM Description: A sample Master-Detail reportREM set page size, line size, new page spacing for screen display. REM set page size, line size, new page spacing for screen display. SET LINESIZE 65SET LINESIZE 65SET PAGESIZE 12SET PAGESIZE 12SET NEWPAGE 1SET NEWPAGE 1REM define department variableREM define department variableCOLUMN pro_dept_number NEW_VALUE dept_number_var COLUMN pro_dept_number NEW_VALUE dept_number_var

NOPRINTNOPRINTREM set column sizes based on alias column namesREM set column sizes based on alias column namesCOLUMN dpt_name FORMAT A18COLUMN dpt_name FORMAT A18COLUMN pro_name FORMAT A15COLUMN pro_name FORMAT A15COLUMN pro_location FORMAT A15COLUMN pro_location FORMAT A15TTITLE CENTER 'Department Number:' dept_number_var SKIP 2TTITLE CENTER 'Department Number:' dept_number_var SKIP 2BTITLE SKIP 1 CENTER 'Not for external dissemination.' BTITLE SKIP 1 CENTER 'Not for external dissemination.'

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-85

• Example cont’dExample cont’d

BREAK ON pro_dept_number SKIP PAGEBREAK ON pro_dept_number SKIP PAGE

SELECT pro_dept_number, dpt_name, pro_name, pro_locationSELECT pro_dept_number, dpt_name, pro_name, pro_location

FROM department d, project pFROM department d, project p

WHERE d.dpt_no = p.pro_dept_number AND WHERE d.dpt_no = p.pro_dept_number AND

pro_dept_number IN (3, 7)pro_dept_number IN (3, 7)

ORDER BY pro_dept_number; ORDER BY pro_dept_number;

• The report produced is shown next. The report produced is shown next.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-86

Department Number: 3Department Number: 3

DPT_NAME PRO_NAME PRO_LOCATIONDPT_NAME PRO_NAME PRO_LOCATION------------------ ----------------- --------------------------------- ----------------- ---------------Admin and Records Inventory MarinaAdmin and Records Inventory MarinaAdmin and Records Pay Benefits MarinaAdmin and Records Pay Benefits Marina

Not for external dissemination.Not for external dissemination.More . . .More . . .

Department Number: 7Department Number: 7

DPT_NAME PRO_NAME PRO_LOCATIONDPT_NAME PRO_NAME PRO_LOCATION------------------ --------------- --------------------------------- --------------- ---------------Production Order Entry St. LouisProduction Order Entry St. LouisProduction Payroll CollinsvilleProduction Payroll CollinsvilleProduction Receivables EdwardsvilleProduction Receivables Edwardsville

Not for external dissemination. Not for external dissemination.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-87

MASTER-DETAIL REPORTSMASTER-DETAIL REPORTS• A typical master-detail report format includes information in the A typical master-detail report format includes information in the

top title report line that identifies the "master column" that top title report line that identifies the "master column" that controls the page breaks.controls the page breaks.

• You can reference a column value in a top title by first storing You can reference a column value in a top title by first storing the column value to a the column value to a program variableprogram variable..

• You then specify the program variable name in the TTITLE You then specify the program variable name in the TTITLE command.command.

• A special form of the COLUMN command is used to define a A special form of the COLUMN command is used to define a program variable as shown below. program variable as shown below.

• The actual COLUMN command from program The actual COLUMN command from program ch9-3.sqlch9-3.sql is also is also shown below. shown below.

• The NEW_VALUE clause defines the variable name. You must The NEW_VALUE clause defines the variable name. You must follow Oracle's naming rules when naming program variables. follow Oracle's naming rules when naming program variables.

COLUMN column_name NEW_VALUE variable_name COLUMN column_name NEW_VALUE variable_name [options] [options]

COLUMN pro_dept_number NEW_VALUE dept_number_var COLUMN pro_dept_number NEW_VALUE dept_number_var NOPRINTNOPRINT

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-88

Using Views in Master-Detail ReportsUsing Views in Master-Detail ReportsREM Program: ch9-4.sqlREM Program: ch9-4.sqlREM Programmer: dbock; 3-20-2003REM Programmer: dbock; 3-20-2003REM Description: The revised Master-Detail program with a REM Description: The revised Master-Detail program with a

View.View.  REM set page size, line size, new page for screen display.REM set page size, line size, new page for screen display.SET LINESIZE 75;SET LINESIZE 75;SET PAGESIZE 12;SET PAGESIZE 12;SET NEWPAGE 1;SET NEWPAGE 1;  REM Create a view to be used in the SELECT command later.REM Create a view to be used in the SELECT command later.CREATE OR REPLACE VIEW project_department (project_no, CREATE OR REPLACE VIEW project_department (project_no,

dept_name,dept_name, project_name, location) ASproject_name, location) AS SELECT pro_dept_number, dpt_name, pro_name, pro_locationSELECT pro_dept_number, dpt_name, pro_name, pro_location FROM department d, project pFROM department d, project p WHERE d.dpt_no = p.pro_dept_number AND WHERE d.dpt_no = p.pro_dept_number AND pro_dept_number IN (3, 7)pro_dept_number IN (3, 7) ORDER BY pro_dept_number; ORDER BY pro_dept_number;

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-89

Using Views in Master-Detail ReportsUsing Views in Master-Detail ReportsCOLUMN dept_name NEW_VALUE dpt_name_var NOPRINTCOLUMN dept_name NEW_VALUE dpt_name_var NOPRINT  COLUMN dept_name FORMAT A18COLUMN dept_name FORMAT A18COLUMN project_name FORMAT A15COLUMN project_name FORMAT A15COLUMN location FORMAT A15COLUMN location FORMAT A15  TTITLE CENTER 'Department Name: ' dpt_name_var SKIP 2 TTITLE CENTER 'Department Name: ' dpt_name_var SKIP 2 BTITLE SKIP 1 CENTER 'Not for external dissemination.' BTITLE SKIP 1 CENTER 'Not for external dissemination.'   BREAK ON project_no SKIP PAGE;BREAK ON project_no SKIP PAGE;  SELECT project_no, dept_name, project_name, locationSELECT project_no, dept_name, project_name, locationFROM project_department;FROM project_department;  • The program creates a view named The program creates a view named project-departmentproject-department. This . This

view assigns meaningful names to the selected columns, joins view assigns meaningful names to the selected columns, joins the the departmentdepartment and and projectproject tables, and orders the output of tables, and orders the output of rows by department number of the department controlling rows by department number of the department controlling each project.each project.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-90

Using Views in Master-Detail ReportsUsing Views in Master-Detail Reports• The revised COLUMN command uses a The revised COLUMN command uses a

NEW_VALUE clause to store the value of the NEW_VALUE clause to store the value of the dept_namedept_name column of the view to a variable named column of the view to a variable named dpt_name_var.dpt_name_var.

• This variable is used in the TTITLE command to This variable is used in the TTITLE command to display the department name at the top of each page. display the department name at the top of each page.

• The BREAK command still breaks on the The BREAK command still breaks on the project_noproject_no column as the master column.column as the master column.

• Finally, the SELECT statement is greatly simplified Finally, the SELECT statement is greatly simplified because the program is now selecting information from because the program is now selecting information from the view.the view.

• If the view had been previously created, then the code If the view had been previously created, then the code to create the view could be deleted from program to create the view could be deleted from program ch9-4.sql.ch9-4.sql.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-91

Department Name: Admin and RecordsDepartment Name: Admin and Records  PROJECT_NO PROJECT_NAME LOCATIONPROJECT_NO PROJECT_NAME LOCATION---------- --------------- ------------------------- --------------- --------------- 3 Inventory Marina3 Inventory Marina Pay Benefits MarinaPay Benefits Marina     Not for external dissemination.Not for external dissemination.More . . .More . . .   Department Name: ProductionDepartment Name: Production  PROJECT_NO PROJECT_NAME LOCATIONPROJECT_NO PROJECT_NAME LOCATION---------- --------------- ------------------------- --------------- --------------- 7 Order Entry St. Louis7 Order Entry St. Louis Payroll CollinsvillePayroll Collinsville Receivables EdwardsvilleReceivables Edwardsville     Not for external dissemination.Not for external dissemination.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-92

USING VARIABLES FOR INTERACTIVE USING VARIABLES FOR INTERACTIVE REPORTINGREPORTING

REM Program: ch9-5.sqlREM Program: ch9-5.sqlREM Programmer: dbock; 3-20-2003REM Programmer: dbock; 3-20-2003REM Description: Program with interactive variables.REM Description: Program with interactive variables.  SET LINESIZE 60;SET LINESIZE 60;SET PAGESIZE 12;SET PAGESIZE 12;SET NEWPAGE 1;SET NEWPAGE 1;  COLUMN today NEW_VALUE date_varCOLUMN today NEW_VALUE date_varSELECT TO_CHAR(SYSDATE, 'MM/DD/YY') todaySELECT TO_CHAR(SYSDATE, 'MM/DD/YY') todayFROM dual;FROM dual;  COLUMN pro_name NEW_VALUE pro_name_var NOPRINTCOLUMN pro_name NEW_VALUE pro_name_var NOPRINTCOLUMN pro_number NEW_VALUE pro_number_var NOPRINTCOLUMN pro_number NEW_VALUE pro_number_var NOPRINTCOLUMN "Department" FORMAT A18COLUMN "Department" FORMAT A18

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-93

USING VARIABLES FOR INTERACTIVE USING VARIABLES FOR INTERACTIVE REPORTINGREPORTING

COLUMN "SSN" FORMAT A12COLUMN "SSN" FORMAT A12COLUMN "Employee Name" FORMAT A20COLUMN "Employee Name" FORMAT A20COLUMN "Hours" FORMAT 999.99COLUMN "Hours" FORMAT 999.99  CLEAR BREAKSCLEAR BREAKSCLEAR COMPUTESCLEAR COMPUTESBREAK ON "Department" ON REPORTBREAK ON "Department" ON REPORTCOMPUTE SUM OF "Hours" ON REPORTCOMPUTE SUM OF "Hours" ON REPORT  ACCEPT project_no_var PROMPT 'Enter a project number: 'ACCEPT project_no_var PROMPT 'Enter a project number: 'PAUSE Press the Enter Key to continue.PAUSE Press the Enter Key to continue.  TTITLE LEFT date_var CENTER 'Project Name: ' pro_name_var -TTITLE LEFT date_var CENTER 'Project Name: ' pro_name_var - RIGHT 'Page:' FORMAT 999 sql.pno SKIP 1 - RIGHT 'Page:' FORMAT 999 sql.pno SKIP 1 - CENTER 'Project Number:' pro_number_var SKIP 2 CENTER 'Project Number:' pro_number_var SKIP 2   

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-94

USING VARIABLES FOR INTERACTIVE USING VARIABLES FOR INTERACTIVE REPORTINGREPORTING

SPOOL project.lstSPOOL project.lst  SELECT pro_number, pro_name, dpt_name "Department",SELECT pro_number, pro_name, dpt_name "Department", SUBSTR(work_emp_ssn,1,3)||'-'||SUBSTR(work_emp_ssn,1,3)||'-'||

SUBSTR(work_emp_ssn,4,2)||'-'||SUBSTR(work_emp_ssn,6,4) SUBSTR(work_emp_ssn,4,2)||'-'||SUBSTR(work_emp_ssn,6,4) "SSN","SSN",

emp_last_name||', '||emp_last_name||', '|| emp_first_name "Employee Name", emp_first_name "Employee Name", work_hours "Hours"work_hours "Hours"FROM project p, assignment a, employee e, department dFROM project p, assignment a, employee e, department dWHERE p.pro_number = a.work_pro_number ANDWHERE p.pro_number = a.work_pro_number AND a.work_emp_ssn = e.emp_ssn ANDa.work_emp_ssn = e.emp_ssn AND d.dpt_no = p.pro_dept_number ANDd.dpt_no = p.pro_dept_number AND p.pro_number = '&project_no_var‘p.pro_number = '&project_no_var‘

ORDER BY pro_number, emp_last_name, emp_first_name;ORDER BY pro_number, emp_last_name, emp_first_name;  SPOOL OFFSPOOL OFF

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-95

Executing Program Ch9-5.SqlExecuting Program Ch9-5.Sql SQL> start ch9-5.sqlSQL> start ch9-5.sqlMore . . .More . . .

TODAYTODAY----------------04/14/0204/14/02

Enter a project number: 30Enter a project number: 30Press the Enter Key to continue.Press the Enter Key to continue.

old 9: p.pro_number = '&project_no_var'old 9: p.pro_number = '&project_no_var'new 9: p.pro_number = '30'new 9: p.pro_number = '30'More . . .More . . .

04/14/02 Project Name: Pay Benefits Page: 104/14/02 Project Name: Pay Benefits Page: 1 Project Number: 30Project Number: 30  Department SSN Employee Name HoursDepartment SSN Employee Name Hours------------------ ------------ -------------------- ------------------------- ------------ -------------------- -------Admin and Records 999-22-2222 Amin, Hyder 5.10Admin and Records 999-22-2222 Amin, Hyder 5.10 999-55-5555 Joyner, Suzanne 19.20999-55-5555 Joyner, Suzanne 19.20 999-88-7777 Markis, Marcia 30.80999-88-7777 Markis, Marcia 30.80****************** -------****************** ------- 55.1055.10

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-96

Defining User VariablesDefining User Variables• You can define variables with the SQL*Plus You can define variables with the SQL*Plus

DEFINE command.DEFINE command.• The command shown here defines a variable The command shown here defines a variable

name_varname_var, and assigns it the value "Bordoloi." , and assigns it the value "Bordoloi."

DEFINE name_var = BordoloiDEFINE name_var = Bordoloi

• If you need to know what variables have been If you need to know what variables have been defined for your working session, enter the DEFINE defined for your working session, enter the DEFINE command by itself at the SQL> prompt and all command by itself at the SQL> prompt and all current variable definitions will be displayed. current variable definitions will be displayed.

• You can also delete a variable with the UNDEFINE You can also delete a variable with the UNDEFINE <variable_name> command.<variable_name> command.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-97

Defining User VariablesDefining User VariablesDEFINE name_var = BordoloiDEFINE name_var = BordoloiSELECT emp_last_name, emp_first_name, SELECT emp_last_name, emp_first_name,

emp_date_of_birthemp_date_of_birthFROM employeeFROM employeeWHERE emp_last_name = '&name_var'WHERE emp_last_name = '&name_var'//

  EMP_LAST_NAME EMP_FIRST_NAME EMP_DATE_ EMP_LAST_NAME EMP_FIRST_NAME EMP_DATE_ ------------------------- -------------------------- ------------------------------------------ -------------------------- -----------------Bordoloi Bordoloi Bijoy Bijoy 10-NOV- 10-NOV-

6767

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-98

Passing Parameter Values Through the Passing Parameter Values Through the START CommandSTART Command

• You can pass a value to a program at run time as a You can pass a value to a program at run time as a parameter of the START command. parameter of the START command.

• Use an ampersand (Use an ampersand (&&) followed by a numeral in the ) followed by a numeral in the command file; for example, command file; for example, &1&1 in place of the in place of the substitution variable.substitution variable.

• Each time you run the command file, the START Each time you run the command file, the START command replaces the command replaces the &1&1 parameter in the file with parameter in the file with the first value (called an argument) listed after a the first value (called an argument) listed after a START START filenamefilename command. command.

• You can use as many ampersand-parameter variables You can use as many ampersand-parameter variables as is needed in the program.as is needed in the program.

• The arguments of the START command are separated The arguments of the START command are separated by commas. by commas.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-99

ExampleExampleREM ch9-6.sql – Example passing argumentsREM ch9-6.sql – Example passing arguments

SELECT emp_last_name, emp_ssn, emp_dpt_numberSELECT emp_last_name, emp_ssn, emp_dpt_number

FROM employeeFROM employee

WHERE emp_last_name = '&1' OR emp_dpt_number = '&2';WHERE emp_last_name = '&1' OR emp_dpt_number = '&2';

REM end of programREM end of program

SQL> start ch9-6.sql Bock 1SQL> start ch9-6.sql Bock 1

old 3: WHERE emp_last_name = '&1' OR emp_dpt_number = '&2'old 3: WHERE emp_last_name = '&1' OR emp_dpt_number = '&2'

new 3: WHERE emp_last_name = 'Bock' OR emp_dpt_number = '1'new 3: WHERE emp_last_name = 'Bock' OR emp_dpt_number = '1'

More . . .More . . .

  

EMP_LAST_NAME EMP_SSN EMP_DPT_NUMBEREMP_LAST_NAME EMP_SSN EMP_DPT_NUMBER

------------------------- --------- --------------------------------------- --------- --------------

Bordoloi 999666666 1Bordoloi 999666666 1

Bock 999111111 7Bock 999111111 7

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-100

Clearing the Computer Monitor ScreenClearing the Computer Monitor Screen

• If you need to clear the computer monitor If you need to clear the computer monitor screen before displaying a report (or at any screen before displaying a report (or at any other time), include the CLEAR command other time), include the CLEAR command with its SCREEN clause at the appropriate with its SCREEN clause at the appropriate point in your command file, using the format point in your command file, using the format shown here. shown here.

CLEAR SCREENCLEAR SCREEN

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-101

Formatting Aggregate Function TitlesFormatting Aggregate Function Titles

• The COMPUTE command produces a standard title of The COMPUTE command produces a standard title of 'sum' as a label for the column that is aggregated. 'sum' as a label for the column that is aggregated.

• This also applies to the other aggregate functions; each This also applies to the other aggregate functions; each function has its own standard title.function has its own standard title.

• SQL*Plus allows you to change the aggregate function SQL*Plus allows you to change the aggregate function title to a more meaningful title.title to a more meaningful title.

• The COMPUTE commands shown below revise those The COMPUTE commands shown below revise those used earlier in program used earlier in program ch9-2.sqlch9-2.sql (run program (run program ch9-ch9-2a.sql2a.sql). ).

• Each employee's sum of total hours worked is labeled Each employee's sum of total hours worked is labeled as 'Employee Hours,' and the report sum of total hours as 'Employee Hours,' and the report sum of total hours is labeled as 'Total Hours.'is labeled as 'Total Hours.'

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-102

COMPUTE SUM LABEL 'Employee Hours' OFCOMPUTE SUM LABEL 'Employee Hours' OF

"Hours Worked" ON "Emp. Soc. Sec. #" "Hours Worked" ON "Emp. Soc. Sec. #"

COMPUTE SUM LABEL 'Total Hours' OF "Hours Worked" ON COMPUTE SUM LABEL 'Total Hours' OF "Hours Worked" ON REPORTREPORT

Following Figure gives pages #1 and #4 of the reportFollowing Figure gives pages #1 and #4 of the report

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-103

Sun Apr 14 page 1Sun Apr 14 page 1 Project InformationProject Information  Emp. Soc. Sec. # Project # Hours WorkedEmp. Soc. Sec. # Project # Hours Worked---------------- ---------- ---------------------------- ---------- ------------999111111 1 31.40999111111 1 31.40 2 8.502 8.50**************** ------------**************** ------------Employee Hours 39.90Employee Hours 39.90    999222222 10 34.50999222222 10 34.50 30 5.1030 5.10**************** ------------**************** ------------Employee Hours 39.60Employee Hours 39.60    999333333 3 42.10999333333 3 42.10**************** ------------**************** ------------Employee Hours 42.10Employee Hours 42.10

Not for external dissemination.Not for external dissemination.

  

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-104

--------- pages 2 and 3 would be printed here ------------------ pages 2 and 3 would be printed here ---------  Sun Apr 14 page 4Sun Apr 14 page 4 Project InformationProject Information  Emp. Soc. Sec. # Project # Hours WorkedEmp. Soc. Sec. # Project # Hours Worked---------------- ---------- ---------------------------- ---------- ------------   ------------------------Total Hours 284.20Total Hours 284.20         Not for external dissemination.Not for external dissemination.  

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-105

Changing Column HeadingsChanging Column Headings • When displaying column headings, you can either use the When displaying column headings, you can either use the

default heading which is the column name, or you can default heading which is the column name, or you can change the heading with the COLUMN command. change the heading with the COLUMN command.

• The COLUMN command's HEADING clause can be used to The COLUMN command's HEADING clause can be used to assign meaningful column headings. assign meaningful column headings.

• If the new heading is a single word, the heading can be typed If the new heading is a single word, the heading can be typed as is done for the as is done for the emp_ssn columnemp_ssn column heading of SSN. heading of SSN.

• If the heading is more than one word, the heading must be If the heading is more than one word, the heading must be enclosed in single or double-quotes as is shown for the enclosed in single or double-quotes as is shown for the emp_last_nameemp_last_name heading of "Last Name." heading of "Last Name."

• If you want to display a column heading on more than one If you want to display a column heading on more than one line, use a vertical bar (|) where you want to begin a new line line, use a vertical bar (|) where you want to begin a new line as is done for the as is done for the emp_first_nameemp_first_name column. column.

Bordoloi and BockBordoloi and Bock Copyright 2004 Prentice Hall, Inc. 8-106

ExampleExample

COLUMN emp_ssn HEADING SSN;COLUMN emp_ssn HEADING SSN;

COLUMN emp_last_name HEADING "Last Name";COLUMN emp_last_name HEADING "Last Name";

COLUMN emp_first_name HEADING COLUMN emp_first_name HEADING "First|Name";"First|Name";

  • The new headings will remain in effect until you enter The new headings will remain in effect until you enter

different headings, reset each column's format, or exit different headings, reset each column's format, or exit SQL*Plus. SQL*Plus.