Sie sind auf Seite 1von 36

Introduction to SQL and Oracle

Part 2. Data Definition Language, Views, SET operations, Formatting the output,

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

The Data Manipulation Language


This is the section of SQL which handles data manipulation, i.e. inserting, updating and deleting rows in tables. It consists of three basic statements INSERT UPDATE DELETE allows insertion of records into a table updates existing rows in a table removes unwanted rows from a table

These statements are incorporated into what is known as a transaction

INSERTing rows into a table


The INSERT INTO statement has a number of forms, as the following examples show INSERT INTO <tablename> VALUES(value1, value2, value3,.....); This form allows insertion of ONE complete row into the table. The values in the list must be in the same order as the columns in the table and there must be a value for each column. So to insert a new row into the EMP table INSERT INTO emp VALUES (7999, cox, CLERK, 7369, 01-APR92, 2000,250,20); If you do not have values for all the columns, a list of columns may be specified and values provided in the same order as the specified columns. INSERT INTO emp(empno, ename, hiredate, deptno) VALUES (7888, PITT, 29-FEB-92, 30); All unspecified columns will be set to NULL. N.B. Only one row at a time may be inserted using the above forms of the INSERT statement.

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

Multiple rows may be inserted by using a SELECT statement to bring in rows from another table. (Obivously this form can not be used for raw data input - only data which already exists in an Oracle table) INSERT INTO bonus (empno, manager, highsal) SELECT empno,ename,sal*1.1 FROM emp WHERE job = MANAGER This takes data about managers from the emp table and copies it into the bonus table.

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

UPDATEing existing rows


The UPDATE statement allows you to change the values of existing rows in an Oracle table. UPDATE <tablename> SET column = value; or more generally UPDATE <tablename> SET (col_1, col_2,...) = val_1, val_2,... WHERE <condition> Values supplied may be derived from expressions e.g. UPDATE emp SET sal = sal*1.1; UPDATE emp SET comm = (SELECT avg(comm)/2 FROM emp); But only one column may be specified if you are using such expressions, hence the following is illegal. UPDATE emp SET (sal,comm) = (sal * 1.25, comm/2); The SELECT statement may be used to provide the new values for the update (as shown above). It may also be used to decide which of the rows in a table should suffer the update UPDATE emp SET comm = (SELECT MIN(comm) FROM emp WHERE deptno = 10) WHERE job = SALESMAN; Remember if a WHERE clause isnt used to limit the number of rows updated, every row in the table will be updated to your specified value.

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

DELETEing unwanted rows


The DELETE statement allows you to remove one or more unwanted rows from a table. Like INSERT, it functions on whole rows of data DELETE FROM emp WHERE ename = JONES; This will delete JONESs record from the emp table. Care must be taken with the DELETE statement. The following statement does not contain a WHERE clause DELETE FROM emp; This will delete every row from the emp table - and it does not even ask for confirmation! Always make sure you use a WHERE clause in any DELETE statement (unless you really want to wipe a table). Incidentally, when a table is wiped, no space is freed up in the Oracle database for use by other tables. The space used by a table does not dynamically shrink when data is deleted from the table.

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

COMMITting the changes


Normally, if you decide that your changes are an error, you may roll them back out of the database by replacing them with the original values. This can be done by issuing the command SQL>ROLLBACK; This will rollback all your changes since the last commit was performed. If you wish to make your changes permanent (which means they will not be able to be rolled back) you should issue the command. SQL>COMMIT; The use of these two commands enables you to design logical units of work (known as transactions). These units consist of a number of DML statements which all should succeed in order to keep the database consistent, or all should be rolled back. This is also known as transaction atomicity - all succeed or all fail (no halfway measures). A typical scenario could be one in which you might wish to change a department number. This change should occur in both the department table and the employee table in order to keep the database consistent. Hence, a COMMIT statement should only be issued after the second update statement and not after the first. If a COMMIT is issued after the first statement, it would be possible for a department to have a new value in the dept table, but employees to be left dangling with an old defunct department number in the emp table. Sometimes Oracle will perform its own implicit commit (no message is given when this happens). Oracle performs an implicit commit whenever 1. the user logs off Oracle in normal fashion 2. immediately before it executes a DDL command 3. immediately after it executes a DDL command Oracle will automatically perform an implicit rollback whenever 1. A user process terminates abnormally Oracle can now perform statement level rollback - see the SQL*Plus Reference Guide

The Data Definition Language


DATABASE MANAGEMENT SYSTEMS
Staffordshire UNIVERSITY

DDL statements change the structure of the database. There are three basic commands CREATE ALTER DROP any used to create new objects (tables, views, etc) in the database used to change the structure of an existing object used to expunge the object from the database (all its data plus reference to it in the data dictionary)

To create a new table use the CREATE TABLE statement CREATE TABLE <tablename> ( col_1 datatype [NULL NOT NULL], col_2 datatype [NULL NOT NULL], ............................); where col_x may be any alphanumeric name starting with an alphabetic character. The name may also contact $ _ # @ (maximum 30 characters) datatype may be one of the following CHAR VARCHAR NUMBER allows variable length alphanumeric data up to 255 characters in length (will change in Oracle 7 to fixed length!) allows variable length alphanumeric data up to 255 characters in length numeric data - maximum of 38 digits (will also accept scientific notation)

NUMBER (W,d) numeric data of total width W and d decimal places DATE LONG dates (including a time element down to seconds) up to 64K of free format text (limited to one LONG per table) LONGs may not be used in functions or WHERE clauses

optionally use NULL or NOT NULL to specify whether the column can accept NULL values. The default is NULL i.e. NULL values are allowed. The CREATE TABLE is progressively becoming more complex - particularly so in Oracle 7. This treatment merely covers the basic statement.

CREATEing a table
CREATE TABLE emp
DATABASE MANAGEMENT SYSTEMS
Staffordshire UNIVERSITY

empno ename job mgr hiredate sal comm deptno

NUMBER(4) NOT NULL, CHAR(12, CHAR(12), NUMBER(4) DATE, NUMBER(7,2), NUMBER(7,2), NUMBER(4) NOT NULL;

Note that NOT NULL is specified for the empno column. This column will be used as the primary key. When a table is created you may specify criteria for its storage (such as initial space allocation). If the storage clause is not used, SQL*Plus will use the current defaults. See the SQL Language Reference Manual or the DBA Guide t V6.

Valid table names


emp2 EMP2 2emp PROJ-ASST PROJ_ASST PROJ ASST PROJ ASST UPDATE OK NO NO OK NO OK NO OK starts with a letter table names are not case-sensitive starts with a number the - is not a valid character use of underscore is recommended to link words spaces are not allowed spaces allowed within double quotes - not recommended reserved word in SQL

Names which are already given to existing objects owned by the user, are also prohibited

ALTERing the table structure


To modify the definition or structure of a table, use the ALTER TABLE command To add a new column

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

ALTER TABEL <tablename> ADD (column_name datatype); e.g. ALTER TABLE emp ADD (GENDER CHAR(1));

To modify an existing column ALTER TABLE <tablename> MODIFY (deptno NUMBER(6)); e.g. ALTER TABLE emp MODIFY (deptno NUMBER(6));

You may not drop or delete a column using ALTER. There is no direct support in SQL for removing columns from a table! You may not rename a column using ALTER. Again there is no direct support in SQL for this. The use of the ALTER TABLE statement to change column definitions is restricted as follows 1. If the table does not contain any data, you may add extra NULL or NOT NULL columns change the datatype of an existing column alter an existing column to be NULL or NOT NULL make the width of the column smaller or larger If the table contains rows, but there are no values in the column in question make the column width smaller or larger change the datatype If the column already has data values make the column width larger (not smaller) force the column to be NOT NULL if there are no NULLs already present in the column

2.

3.

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

DROPping objects from the database


The DROP statement may be used to remove entire unwanted objects from the database. It frees up any space they were occupying and removes all references to them from the data dictionary. (Only the creator of the table may DROP it) DROP TABLE <tablename>; will remove the specified table (with its contents) from the database. It will also remove any indexes which are based on that table. Remember that this statement is very severe and should be used with extreme caution No confirmation is requested by Oracle in order to perform this operation Oracle issues an implicit commit both before and after it processes the DROP command. This means you cannot even roll it back.

Good back up and recovery procedures need to be in place if this type of statement could possibly be used in error. The DROP statement may be used to drop tables, views, indexes, synonyms etc., but it may not be used to drop columns. Deleting columns from tables can not be done directly. One method which may be used is as follows:To delete the column LOC from the dept table 1. Create a new table which is an angle of the dept table excluding the LOC column CREATE TABLE newdept AS SELECT deptno, dname FROM dept; this produces a table containing all the data for deptno and dname which already exists in the dept table. Column headings will default to those in the dept table. 2. Now drop the old table DROP TABLE dept; 3. Rename the new table to the old table name RENAME newdept TO dept;
DATABASE MANAGEMENT SYSTEMS
Staffordshire UNIVERSITY

VIEWS Views can be regarded as windows through which users may see data stored in database tables. They have a number of attractive features:(i) they do not own any data of their own
hence they take up virtually no space in the database (in fact the only space consumed is that required for their definition in the relevant data dictionary tables)

(ii)

they are automatically activated when the user references them in an SQL statement
this means they will always reflect the current state of the database

(iii)

they may be simple or arbitrarily complex


views may be based on single or multiple tables and may also reference other views views may be tailored to suit user requirements and make the users task easier (e.g. avoid specification of complex joins) simple views are based on a single table and only contain columns which are directly stored in the table in question

(iv)

views are merely stored SQL statements


hence they can be defined using familiar SQL constructs

(v)

may be treated as tables in SQL queries


almost 100% compatible with table usage

(vi)

can be used to implement row level security within SQL *Plus


the GRANT statement does not provide this functionality

(vii) may be used to implement integrity (including referential) checks


Oracle7 will use constraints to perform this function

(viii) useful in providing a level of data independence for application programs


their use allows the structure of the database to change with minimal effect on users and application programs

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

VIEW MANAGEMENT View definitions may be observed using the following dictionary views USER_VIEWS ALL_VIEWS DBA_VIEWS

these show the viewnames along with the full view definitions Views may be created using the CREATE VIEW <viewname> command. (Remember no storage definition will be required.) They may be dropped using the DROP VIEW <viewname> command. It is important to realise that views may not be altered - they are essentially stored SQL statements. So for complex views, it may be advisable to save their definitions in a command file in case they subsequently need to be changed. With this, you merely drop the view and run your amended view definition file. Note that when a table is dropped or becomes inaccessable, any views built on that table will remain in existance but will become invalid. When using a DBA account do not be tempted to update view definitons as stored in the data dictionary - DML should never be performed on the dictionary tables. The use of views can present a performance overhead, mainly in increased parse times. Remember also that Verson 6 does not possess a view cache, so there is a probable increase in disk I/O when views are used.

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

CREATEing Views The CREATE VIEW command allows you to create a view by specifying a standard SQL query: CREATE VIEW <viewname> [(col_1,col_2,....)] AS SELECT ename, sal, comm FROM emp WHERE deptno = 30; At this point Oracle will reply with View created. The view can be used and referenced as you would a normal Oracle table SELECT ename, sal FROM dept30 WHERE comm IS NOT NULL; Complex views can be used to make life easier for the user and also to present virtual columns (columns which do not exist in the database) CREATE VIEW total_comp (employee, job, salary, commission, annual_sal, total AS SELECT ename, job, sal, NVL(comm,0), sal*12, sal*12 + NVL(comm,0) FROM emp; Views which contain virtual columns MUST have their own column headings specified. In the above example, annual_sal respresents sal*12 from the base table. Views cannot contain an ORDER BY clause - this must be specified outside of the view in the normal SELECT statement e.g. SELECT * FROM dept30 ORDER BY sal;

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

Views - Data Manipulation As already seen, views have a number of attractive features. It is tempting to make heavy use of views. Remember that they can be treated as base tables (queries will work just as effectively against views as they will against base tables almost 100% of the time). However, one will encounter some very serious problems when attempting to manipulate data through views. The ability to perform DML operations on views in an Oracle database is currently severely restricted. This can only be performed on what are known as simple views. Often there are good reasons for this. Consider the following view definition: CREATE VIEW summary AS SELECT deptno, avg(sal) FROM emp GROUP BY deptno; This view contains an aggregate function which renders all the data seen through the view non-updatable. Views on more than one table suffer similar restrictions: CREATE VIEW deptemp AS SELECT empno, ename, hiredate, sal, comm, deptno, dname, loc FROM emp, dept WHERE emp.deptno = dept.deptno; The output from such a view would look like
EMPNO ENAME HIREDATE SAL 2000 COMM 500 DEPTNO 30 DNAME SALES LOC

--------7777 CHICAGO

--------COX

-----------11-APR-92

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

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

----------

What if the user wishes to delete COXs details from the view? They would probably attempt the following operation DELETE FROM deptemp WHERE ename = COX; Obviously Oracle has a problem because this would probably translate into two separate deletes on the two tables. If this were allowed to go ahead we could easily find the remaining employees in COXs department having no correspondence department record in the department table.

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

In fact all DML operations on views based on more than one table are disabled. This is somewhat over protective as, theoretically, many of the possible update operations should be allowed - e.g. a simple salary change.

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

UPDATEing Views The Rules 1. Views containing GROUPed set of data: no DML is allowed on any column in the view 2. Views based on the join of one or more tables (or views): no DML is allowed on any column in the view 3. Views containing virtual columns (e.g. sal + comm): updates allowed on all but the virtual columns delete operations are unrestricted inserts are allowed if - all not null columns are specified and no attempt is made to insert a value in any of the virtual column(s) Hence given the view CREATE VIEW virtualcols AS SELECT empno, ename, sal, comm, sal + comm total FROM emp; The following statements are legal UPDATE virtualcols SET sal = 9999 WHERE empno = 7934; INSERT INTO virtualcols VALUES (7777, COX, 8888, 1111) The following statements are illegal UPDATE virtualcols SET total = 9999 WHERE empno = 7934; INSERT INTO virtualcols VALUE (7777, CoX, 8888, 1111, 9999); 4. Simple views which do not possess ALL of the NOT NULL columns: no INSERTion of rows is possible (only updates and deletes) 5. Views containing the WITH CHECK OPTION

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

Updates are restricted to those which result in data which still compiles with the check (data migration is prevented) - see table constraints in Oracle7

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

VIEWS - Logical Data Independence Suppose we have this data model, where each project may have a number of employees but each employee may only be assigned to one project. Project Employee

The tables built to handle this situation would probably look like: PROJECT Projno --------101 102 103 Pname --------alpha beta psi Budget --------9,600 10,100 54,000 EMPLOYEE Empno --------7369 7499 7782 7932 7654 7788 Ename --------smith ford allen ward james scott Sal ------2000 3000 1800 1500 1600 5000 Projno -------101 101 102 101 103 102

For convenience we could create a view based on these tables: CREATE VIEW pers AS SELECT ename, sal, pname FROM employee e, project p WHERE e.projno = p.projno; This view is designed to display information on employees and their projects as shown below and can obviously be referenced in application programs Pers Ename --------smith allen Sal ----2000 1800 Pname --------alpha beta

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

Now suppose the rules change such that employees may be assigned to more than one project. This small change in the requirements will result in a massive change in the database design. If we take a look at the new entity model we will see that there is now a many to many relationship between employees and their projects.

Project

Employee

This relationship must be resolved by the introduction of a new entity (intersecting entity) to hold details of who is working on which project.

Project

Employee

Assignments
The following tables now have to be constructed - a significant design change. Project Projno -------101 102 103 Pname -------alpha beta psi Budget --------9,600 10,100 54,000 Employee Empno --------7369 7499 7782 7932 7654 7788 Ename -------smith ford allen ward james scott Sal ---2000 3000 1800 1500 1600 5000

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

Assignment Projno -------101 101 102 Empno --------7369 7499 7369 Start_Date ------------03-apr-90 01-apr-90 25-dec-89 End_Date -----------04-apr-90 31-apr-90 31-dec-89

View Maintenance
DATABASE MANAGEMENT SYSTEMS
Staffordshire UNIVERSITY

This change could cause a hiatus with our application programs. However in terms of using the pers view, we can cope with the new table structure as follows. First drop the old view (views may not be altered) DROP VIEW pers; A new view must now be created which will display the same data as the old view but handles the change in table structure. CREATE VIEW pers AS SELECT ename, sal, pname FROM employee e, project p, assignment a WHERE e.empno = a.empno AND p.projno = a.projno; At this stage it is worth remembering that the employee table will still contain values for projno. As columns may not be dropped from tables, these values must be set to NULL. Alternatively, a new image of the employee table may be created which excludes the projno column. If applications have referenced the view called pers they will now still work without modification. Obviously if applications reference the underlying base tables, they would need to undergo significant changes.

SET operations
Oracle possesses a number of functions which can be used to perform set (as in mathematics) operations

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

These are UNION INTERSECT MINUS They are normally applied across two or more SELECT statements e.g. SELECT ......... FROM ......... UNION SELECT ......... FROM .........

UNION
This operator presents rows which are returned by any of the SELECT statements involved in the query (if effectively Ors the results of the SELECT statements)

SELECT ename, sal FROM emp WHERE job = MANAGER UNION SELECT ename, sal FROM emp WHERE deptno = 10;
Employees names and salaries are returned for both managers and all people in department 10 Obviously the above statement could have been performed using an OR e.g.

SELECT ename, sal FROM emp WHERE job = MANAGER OR deptno = 10;
The UNION operator, however, is more general than the OR operator in that it can work across tables - e.g.

SELECT ename, sal FROM emp WHERE job = MANAGER UNION SELECT ename, sal FROM consultants WHERE contract_date> 01-MAY-92;

UNION operations
The same number of columns must be selected by all query blocks in the UNION statement. The columns must also be of the same datatype and in the same order they do not have to have the same name. The final presented column will have the same heading as the one specified in the first selected statement. So
DATABASE MANAGEMENT SYSTEMS
Staffordshire UNIVERSITY

SELECT ename, sal, deptno FROM emp WHERE deptno = 10 UNION SELECT ename, comm, deptno FROM emp WHERE deptno = 30; will produce as follows ENAME ---------SMITH FORD : SAL ----2000 230 : DEPTNO -----------10 30 :

notice sal and comm values are mixed under the heading SAL Beware that when using UNIONs, duplicate rows are automatically eliminated! This is NOT the case when using OR - the DISTINCT keyword is required. Incidentally DISTINCT can not be used in direct association with the UNION keyword. [ Oracle at present has no support for OUTER UNIONs ]

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

INTERSECT operator
The INTERSECT operator effectively performs an AND across two select statements in order to present only those rows returned by both select statements. Of course more than one intersect may be used where numerous select statements are involved. SELECT ename, sal FROM emp WHERE job = MANAGER INTERSECT SELECT ename, sal FROM emp WHERE deptno = 10; This query will show only those employees who are both managers and work in department 10. In practice, the INTERSECT operator is not nearly as useful aas UNION.

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

MINUS operator
The MINUS operator is used to present rows which are returned by one select statement but NOT by the second select statement. It is important to be clear about the order of the select statements - viz: SELECT job FROM emp WHERE deptno = 10 MINUS SELECT job FROM emp WHERE deptno = 20; this gives the value PRESIDENT whereas if the selects are placed in a different order SELECT job FROM emp WHERE deptno = 20 MINUS SELECT job FROM emp WHERE deptno = 10; gives the value ANALYST

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

The EXISTS operator


This operator returns only true and false and is used in connection with the subquery construct. A typical example SELECT deptno, dname, loc FROM dept WHERE EXISTS (SELECT deptno FROM emp WHERE job = CLERK); this returns details of departments which employ clerks. A further example SELECT * FROM emp x WHERE NOT EXISTS (SELECT 1 FROM emp WHERE x.empno = mgr) Shows employees who do not manage anyone else. (There are six of them). This type of statement is known as a correlated subquery. A value, x.empno, is passed down from the outer query block to the inner query block for each row in the emp table. Note the use of a table alias in order to distinguish between values from the two images of the emp table. Unlike other subqueries, it is re-executed for each row in the table referenced by the outer query. (In all other examples the subquery is executed only once in order to return a value to the outer query) Incidentally this could perhaps have been atttempted using a NOT IN construct. SELECT * FROM emp WHERE empno NOT IN (SELECT mgr FROM emp); Unfortunately, this returns no rows! The cause of this is the existence of a NULL value in the mgr column. A data item can never not be equal to a NULL and hence the subquery returns no rows. If the NULL is updated to some spurious value such as 9999, the NOT IN subquery will produce the expected result. [The NOT IN subquery construct is to be avoided. Not only does it give unexpected results - but it also has a performance penalty in index usage is disabled]

Formatting the query output

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

SQL*Plus commands can be used to perform rudimentary formatting of SQL output for reporting purposes and controlling the SQL environment. Typically one can give SQL output a title, summary values, new column headings and formats, page numbers. SQL*Plus commands are treated as separate statements from normal SQL statements. Normally they are executed as part of a command file and are specified in advance of an SQL query statement. They cannot simply be RUN with SQL statements because the SQL processor is only able to process SQL statements, but they can be executed singly at the SQL prompt. The SET command This command allows control of the SQL*Plus environment. It gives the user the ability to set various features to a value, or turn them on or off. SQL*Plus commands like these may be specified in a GLOGIN.SQL file which means they will be active (in the sense of setting default values) on a global scale for all user sessions, or in a LOGIN.SQL file. The LOGIN.SQL file is a user- owned file which can be used to set defaults for a user. Unlike SQL reserved words, all SQL*Plus commands may be abbreviated. In the examples which follow the part of the command which may be abbreviated is enclosed in square brackets. The default value for the option is shown by an underscore and the available options are separated by a vertical bar l. Examples SET PAUSE ON
this command causes a pause to occur after each new page of output - the user must press <RETURN> in order to progress to the next page governs the display of commands as they are executed from a command file. Obviously OFF suppresses the display.

SET ECHO OFF/ON SET FEED[BACK] 6/N/OFF/ON

SET HEA[DING] OFF/ON SET LIN[ESIZE] 80IN

setting feedback to a value governs when Oracle displays the number of records retrieved message after each query. If 6 or more receords are retrieved, the message is shown by default. This can be overriden by specifying your own value or turning feedback OFF altogether. Turning feedback ON puts the number of records at 1. governs the printing of column headings in SQL output sets the total characters shown on each line of Oracle output. The maximum value of n is 500 but obviously other restrictions may prevail.

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

SET NEW[PAGE] 1 IN
to zero,

specifies number of blank lines to be printed between bottom title of one page and the top title of the next page. If n is set Oracle will force a formfeed between pages. sets a default value for the format for the display of numeric columns governs the default width for the display of numeric values sets the number of lines per page message governs whether Oracle will wait for user input (a press of the <RETURN> key) or not. Message governs the printed on the screen when Oracle waits for input. sets the number of spaces between columns in any output. The maximum value is 10. when set to ON, this will display timing statistics for each SQL statement which is subsequently executed. (The information shown is O/S dependent). governs whether SQL output will actually be shown on the terminal screen. Obviously useful if output is meant to be directed to a file. controls the truncation of a data item if it is too long for the current line width. OFF truncates the data, ON allows it to wrap to the next line.

SET NUMF[ORMAT] <format> SET NUMW[IDTH] 10IN SET PAGES[IZE] 14IN SET PAUSE ON/OFF
prompt

SET SPA[CE] 1 /N SET TIM[ING] ON/OFF

SET TERM[OUT] ON/OFF

SET WRA[P] ON/OFF

There is also a SHOW command which may be used to show the current setting of any of the above environment variables - e.g.

SHOW LINESIZE

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

Column Formatting
SQL*Plus commands may be used to specify individual formatting of columns. By default all SQL output is displayed in columnar format, each column heading will be the same as the column name in the database or the expression which is used in the SELECT statement. The following query: SELECT ename, empno, hiredate, sal*12 + NVL (comm,0), deptno FROM emp; will give the following formatted output ENAME ---------MILLER EMPNO ---------7788 HIREDATE --------------12-MAR-92 SAL*12 + NVL ------------------2850 DEPTNO -----------10

Note that column names are in upper case and are all underlined by-. Numeric columns are 10 character columns wide and right justified. Character columns default to the actual column width specification in the database. Date columns are 9 character columns wide. SQL*Plus can be used to change all of these default settings. Remember that any column formatting will remain in place for the whole of the SQL*Plus session unless explicitly turned off or changed. Changing column names SQL> COLUMN ename HEADING Employee Column names may also be changed withing the SQL statement but this only takes effect within that particular select command - e.g. SELECT ename Employee FROM emp; (ename renamed to Employee)

Column names may be forced over more than one line (useful for narrow columns of data as it allows a full display of the column name). COLUMN empno HEADING Employee 1 number (note the use of l to force a new line) Changing column formats (for full details, see the SQL*Plus Users Guide)
COLUMN sal FORMAT $99,999.99 COLUMN HIREDATE A35 COLUMN lotsofchars FORMAT A25 WORDWRAP
2300 ---- > $2,300.00 column width is increased from 9 to 35 characters

wide column is wrapped around at the end of the last word to fit on one line
Staffordshire UNIVERSITY

DATABASE MANAGEMENT SYSTEMS

If the data value is too big for the column formatting, SQL*Plus displays #### If the data is of the wrong type for the specified format, SQL*Plus displays % The LIKE command allows specification of a column to be the same as a previously specified column COLUMN sal FORMAT $9999 COLUMN comm LIKE sal The NEW_VALUE facility allows you to extract a value in a column for use in the top title of a report page COLUMN job NEW_VALUE jobpage TTITLE RIGHT jobpage This puts the current value of job on the top of each page. Obviously this would be used for data which is grouped around the job column (normally by use of the BREAK statement). Each jobs data will then be printed on one page containing the value of job in its title. The keywork NULL can be used to specify what should be output if a NULL value is encountered in the database for a particular column COLUMN comm FORMAT $999.99 HEADING Commission NULL NotApp

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

Page Titles
Page titles are specified using: TTITLE BTITLE top of page before the displayed SQL output bottom of page after the SQL output

The commands allow text to be shown as titles and positioned LEFT, RIGHT or CENTRE. Text may also be tabbed (moved forward n spaces by using TAB n) or positioned to a specific character column (COL n). Once set, titles remain active for all reports generated within a session, until they are cleared or turned off using TTITLE OFF BTITLE OFF CLEAR TITLE Titles which are turned off may be turned on again (use TTITLE ON). Titles which are cleared, can not be brought back. The SKip command Lines may be skipped using SKIP n (N.B. a value of 0 for n will cause a skip back to the start of the current line). This command can also be used to skip to a new page - SKIP PAGE. If SKIP is used, page number and date are not shown. Displaying values within titles SQL.PNO SQL.LNO SQL.USER any user variable (usually a column NEW_VALUE) Some examples showing the use of TTITLE TTITLE LEFT Company Annual Report TTITLE SKIP 2 COL 10 Departmental Accounts

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

FORMAT may also be used to format the data items in the title TTITLE LEFT FORMAT 099 Page: SQL.PNO CENTER. Departmental Report TTITLE CENTER Company Report SKIP 2CENTER Chemicals Division TTITLE LEFT today CENTER Sales Statistics
[ today would be defined by the NEW_VALUE facility from SYSDATE COLUMN SYSDATE NEW_VALUE today ]

With some releases you could also reformat today to show the new time on each page of the report. TTITLE RIGHT today FORMAT Ddth Mon YY HH:MM:SS

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

BREAK processing
BREAK ON level [action [action]]......... The BREAK command is used to specify where in a report certain actions should occur. These actions may be calculations of summary values, skipping lines, printing (or not) of duplicate values. A break may be specified to occur at any (or all) of the following levels.
ON REPORT ON column name 1 expression useful for producing grand totals at the end of a report or skipping pages before the next report useful for producing summary values and formatting whenever a value of the specified column or expression changes. N.B. This command should only be used with an SQL statement which produces sorted data - usually via an ORDER BY clause. causes break processing to occur after each row in the output. An action should always be specified in this statement. breaks on each page throw

ON ROW

ON PAGE

The actions may be to suppress duplicate values, start a new page or skip lines. A separate COMPUTE statement is required to produce summary values. Some examples BREAK ON REPORT BREAK ON ROW SKIP 2 BREAK ON PAGE BREAK ON deptno SKIP 2 BREAK ON job SKIP PAGE BREAK ON deptno ON job BREAK ON dname SKIP 1 ON job SKIP PAGE To view your breaks, simply type BREAK To clear breaks, type CLEAR BREAKS

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

The COMPUTE statement


This statement is used in conjunction with the BREAK statement in order to produce summary values on groups of rows. An obvious use is in producing subtotals and grand totals. For example: COMPUTE SUM OF sal ON deptno will produce salary totals each time the value of deptno changes if
i) ii) iii) BREAK is specified on deptno and it is the most recently specified BREAK the column (or expression) referenced in the ON clause is in the select list of the SQL statement all expressions, columns, or column aliases in the OF clause must also occur in the select list of the SQL statement

besides SUM you may calculate and display COUNT count of non-null values AVG MAX MIN STD NUM[BER] count of number of rows If a column is renamed inside the SQL query, its alias must be used in BREAK and COMPUTE statements. A typical command file to generate a report. SET PAGESIZE 66 COLUMN sysdate NEW_VALUE today COLUMN comm NULL N/A COLUMN total FORMAT $99,999.99 TTITLE LEFT FORMAT 099 Page: SQL.PNO CENTER Departmental Records SKIP 2 BREAK ON REPORT ON dname SKIP 2 COMPUTE SUM OF sal comm total ON dname COMPUTE SUM OF total ON REPORT SELECT dname, job, empno, sal, comm, nvl(sal,0) + nvl(comm,0) total FROM emp, dept WHERE emp.deptno = dept.deptno ORDER BY dname, sal; CLEAR BREAKS TTITLE OFF

Interactive Queries
DATABASE MANAGEMENT SYSTEMS
Staffordshire UNIVERSITY

Substitution variables which allow the user to specify values to be used at runtime, may be specified in a command file or SELECT statement. This may be done by prefixing the variable with an ampersand (&). For example, the following SQL statement will allow the user to specify which employee records should be displayed based on the value of the sal column. SELECT empno, ename, job, deptno FROM emp WHERE sal = &salary_value; When this statement is executed, SQL*Plus will prompt for the value of salary_value as follows Enter value for salary_value: EMPNO ---------3333 4444 ENAME ----------COX WILKINS 3000 JOB -----MANAGER CLERK DEPTNO -----------10 20

Substitution variables may be used to represent any reference to columns, expressions, or tables. A stored command may use up to 9 parameters. SELECT deptno, AVG(&your_first_column), AVG(&your_second_column) FROM emp WHERE deptno = &department_number If the required substitution is a string, the user must enclose the input with single quotes. Enter value for your_job: ANALYST

this can be avoided by putting the subscription variable in quotes withing the SQL statement SELECT * FROM emp WHERE jon = &yourjob;

Interactive Queries
Often the substitution variable will need to be referenced more than once in a statement - viz.:
DATABASE MANAGEMENT SYSTEMS
Staffordshire UNIVERSITY

SELECT ename, sal, deptno FROM emp WHERE job = &your_job AND sal > (SELECT AVG(sal) FROM emp WHERE job = &your_job; This query is designed to find all those employees who earn more than the average salary for their occupation. When this is run, the user will be prompted twice for the same data! This can be prevented by prefixing the substitution variable with a double ampersand. SELECT ename, sal, deptno FROM emp WHERE job = &&your_job AND sal > (SELECT AVG(sal) FROM emp WHERE job = &&your_job; SQL*Plus will continue to use the supplied value in subsequent queries and will not prompt for your_job until it is explicitly UNDEFINEd. For further details on interactive control see ACCEPT, DEFINE, UNDEFINE and VERIFY in the SQL*Plus reference manual.

DATABASE MANAGEMENT SYSTEMS

Staffordshire UNIVERSITY

Das könnte Ihnen auch gefallen