Upload
zuwena
View
66
Download
1
Embed Size (px)
DESCRIPTION
Oracle SQL introduction. 使用聲明. 請尊重智慧財產權 本資料僅限高雄應用科技大學資管系教學使用 未經允許請勿擅自複製、散佈、使用. Agenda. Database Structure Overview Oracle SQL* Net (Networking) SQL Data Retrieval Data Manipulation Language (DML) Data Definition Language (DDL) Transaction Control Database Objects - PowerPoint PPT Presentation
Citation preview
Oracle SQL introduction
使用聲明
請尊重智慧財產權 本資料僅限高雄應用科技大學資管系教學使用 未經允許請勿擅自複製、散佈、使用
Agenda
Database Structure Overview Oracle SQL* Net (Networking) SQL
– Data Retrieval– Data Manipulation Language (DML)– Data Definition Language (DDL)– Transaction Control
Database Objects– Table, Constraint , Sequence , View , Index
DAY 1
Terminology
Instance (SGA + background process) Database (control file + data file + redo files) Tablespace Schema Object
– Table,Index,Sequence,View,Package,Procedure,Function,Cluster…etc
Database Structure Overview
Control Control FileFile
Redo log FilesRedo log Files
Data Data FilesFiles
ParameterParameter FileFile
Archived Archived Log FileLog File
InstanceInstance DatabaseDatabase
SGASGA
SharedSharedPoolPool
LibraryLibraryCacheCache
Data Dict.Data Dict.CacheCache
DatabaseDatabaseBufferBufferCacheCache
Redo logRedo logBufferBuffer
SMONSMON
DBW0DBW0
PMONPMON
CKPTCKPT
LGWRLGWR
ARC0ARC0
UserUserProcessProcess
ServerServerProcessProcess
Stages in Startup and Shutdown
OPENOPEN
MOUNTMOUNT
NOMOUNTNOMOUNT
SHUTDOWNSHUTDOWN
STARTUPSTARTUP
SHUTDOWNSHUTDOWN
How to determine Database up or down ? (Windows)
How to determine Database up or down ? (UNIX)
Database & Tablespace
Tablespace & Database object
Oracle E-Business Suite Tablespace Design
SYSTEM
TEMP
RBS
FNDD FNDX
GLD GLX
OED OEX
Establishing Connections to Oracle Servers
How to determine Listener up or down?(Windows)
How to determine Listener up or down?(Unix)
Starting and using the Net Configuration Assistant
tnsnames.ora
SEMPROD = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 10.64.32.53 )(PORT = 1520))) (CONNECT_DATA = (SERVICE_NAME = PROD)) )SEMUAT2 = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 10.64.32.54 )(PORT = 1529))) (CONNECT_DATA = (SERVICE_NAME = UAT2)) )
SQL*Plus
Logging into Database
開始 程式集 Oracle 9i Application Development SQL Plus
Logging into Database
SQL*Plus Command Summary (I)
@ & get edit execute host list /
SQL*Plus Command Summary (II)
spool connect describe column set show all exit help
3rd Party Tools
TOAD (Quest Software) SQL Navigator (Quest Software)
Exercise 1
Installation Oracle 9i Database Create Database Connect to Database by SQL* Net (using SQL* Plus) show user
Sample Schema Diagrams
SQL Statement
Data Retrieval– Select
Data Manipulation Language (DML)– Insert,Update,Delete
Data Definition Language (DDL)– Create,alter,drop,rename,truncate
Transaction Control– Commit,rollback,savepoint
Data Control Language (DCL)– Grant,revoke
SQL
Displaying Table Structure
Basic SELECT Statement
SELECT column [alias]FROM table [table alias]WHERE column = ‘xxx’
SELECT column [alias]FROM table [table alias]WHERE column = ‘xxx’
Not Case Sensitive Can be one or more lines Keywords can not be abbreviated or split across
lines
Selecting All Columns, All Rows
Selecting Specific Columns
Arithmetic Expressions
Concatenation Operator
Concatenation Operator
Managing Null Values
NULL is a value that is unavailable,unassigned,unknown,or inapplicable
NULL is not the same as zero or space Arithmetic expressions containing a null value evaluate to NUL
L
Conditions containing NULL
Conditions containing NULL (example)
NVL function
Converts null to an actual value Datatype that can be used are date,character,and nu
mber Datatype must match
– NVL(comm,0)– NVL(hiredate,’01-JAN-97’)– NVL(job,’Not Job Yet’)
NVL Function (example)
DECODE Function
Facilitates conditional inqueries by doing the work of a CASE or IF-THEN-ELSE statement
DECODE (col/express, search1, result1 [ ,search2,result2,……] [, default ])
DECODE (col/express, search1, result1 [ ,search2,result2,……] [, default ])
Using the DECODE Function (example)
Built-in Function Quick Ref.
Preventing the Selection of Duplicate Rows
The default display of queries is all rows including duplicate rows
Eliminate duplicate rows by using DISTINCT in the SELECT clause
SQL>SELECT JOB_ID 2 FROM EMPLOYEES;
SQL>SELECT JOB_ID 2 FROM EMPLOYEES;
SQL>SELECT DISTINCT JOB_ID 2 FROM EMPLOYEES;
SQL>SELECT DISTINCT JOB_ID 2 FROM EMPLOYEES;
Preventing the Selection of Duplicate Rows(example)
SQL>SELECT JOB_ID 2 FROM EMPLOYEES;
JOB_ID--------------------SA_MANSA_REPSA_REPSA_REPSH_CLERKSH_CLERK
SQL>SELECT JOB_ID 2 FROM EMPLOYEES;
JOB_ID--------------------SA_MANSA_REPSA_REPSA_REPSH_CLERKSH_CLERK
Display All Rows
SQL>SELECT DISTINCT JOB_ID 2 FROM EMPLOYEES;
JOB_ID--------------------AC_ACCOUNTAC_MGRAD_ASSTAD_PRESAD_VPFI_ACCOUNTFI_MGRHR_REP
SQL>SELECT DISTINCT JOB_ID 2 FROM EMPLOYEES;
JOB_ID--------------------AC_ACCOUNTAC_MGRAD_ASSTAD_PRESAD_VPFI_ACCOUNTFI_MGRHR_REP
Display Unique Rows
Duplicate Rows
Limiting Selected Rows
Comparison and Logical Operations
Logical comparison operators= > >= < <=
SQL comparison operators– BETWEEN ... AND– IN (list)– LIKE– IS NULL
Logical operators– AND– OR – NOT
The WHERE Clause
SELECT first_name,last_name,job_idFROM employeesWHERE first_name = 'John‘;
SELECT first_name,last_name,job_idFROM employeesWHERE first_name = 'John‘;
FIRST_NAME LAST_NAME JOB_ID--------------- ------------------------------ ----------------John Chen FI_ACCOUNTJohn Seo ST_CLERKJohn Russell SA_MAN
FIRST_NAME LAST_NAME JOB_ID--------------- ------------------------------ ----------------John Chen FI_ACCOUNTJohn Seo ST_CLERKJohn Russell SA_MAN
Negating Expressions
Logical Operators– != <> ^=
SQL Operator– NOT BETWEEN ... AND ...– NOT IN– NOT LIKE– IS NOT NULL
The ORDER BY Clause
Exercise 2
Installing the Human Resources (HR) Schema 列出薪資超過 10000 之員工姓名 , 受雇日期 , 部門及薪資 列出所有銷售部門的員工編號 , 姓名及薪資 , , 並依受雇日
期做 sorting (descending)
Oracle Date Format
Oracle stores dates in a internal numeric format(Valid date range from January 1, 4712 BC to December 31, 9999 AD)
– Century,year,month,day,hours,minutes,seconds Default date display is DD-MON-RR SYSDATE is a function returning date and time DUAL id a dummy table used to view SYSDATE
RR Date Format
RR Date Format (examples)
SELECT TO_CHAR(TO_DATE(’27-OCT-98’, ’DD-MON-RR’) ,’YYYY’) "Year"FROM DUAL;
Year----1998
SELECT TO_CHAR(TO_DATE(’27-OCT-98’, ’DD-MON-RR’) ,’YYYY’) "Year"FROM DUAL;
Year----1998
SELECT TO_CHAR(TO_DATE(’27-OCT-17’, ’DD-MON-RR’) ,’YYYY’) "Year"FROM DUAL;
Year----2017
SELECT TO_CHAR(TO_DATE(’27-OCT-17’, ’DD-MON-RR’) ,’YYYY’) "Year"FROM DUAL;
Year----2017
YY Date Format (examples)
SELECT TO_CHAR(TO_DATE(’27-OCT-98’, ’DD-MON-YY’) ,’YYYY’) "Year"FROM DUAL;
Year----2098
SELECT TO_CHAR(TO_DATE(’27-OCT-98’, ’DD-MON-YY’) ,’YYYY’) "Year"FROM DUAL;
Year----2098
SELECT TO_CHAR(TO_DATE(’27-OCT-17’, ’DD-MON-RR’) ,’YYYY’) "Year"FROM DUAL;
Year----2017
SELECT TO_CHAR(TO_DATE(’27-OCT-17’, ’DD-MON-RR’) ,’YYYY’) "Year"FROM DUAL;
Year----2017
Display the current date
SQL> SELECT SYSDATE FROM DUAL;
SYSDATE----------------11-OCT-03
SQL> SELECT SYSDATE FROM DUAL;
SYSDATE----------------11-OCT-03
SQL> SELECT TO_CHAR(SYSDATE,’YYYY-MM-DD HH24:MI:SS’) FROM DUAL;
TODAY--------------------------------------2003-10-11 23:07:01
SQL> SELECT TO_CHAR(SYSDATE,’YYYY-MM-DD HH24:MI:SS’) FROM DUAL;
TODAY--------------------------------------2003-10-11 23:07:01
Date Function
MONTHS_BETWEEN(date1,date2) ADD_MONTHS(date,n) NEXT_DAY(date,’char’) LAST_DAY(date) ROUND(date,’fmt’) TRUNC(date,’fmt’)
Exercise 3
列出年資超過 3 年的員工姓名 , 薪資 , 受雇日期
Displaying Data from Multiple Tables
What is a join ?
A Join is used to query data from more than one table
Rows are joined using common values, typically primary and foreign key values
Join methods– Equijoin– Non-equijoin– Outer Join– Self Join
Simple Join Query : Syntax
Write the join condition in the WHERE clause Column names must be prefixed with the table name
when the same column name appears in more than one table
Precede each column name with the table name for clarity
SELECT table1.column,table.columnFROM table1,table2WHERE table1.column1=table2.column2;
SELECT table1.column,table.columnFROM table1,table2WHERE table1.column1=table2.column2;
Cartesian Product
A Cartesian product is formed when– A join condition is omitted – A join condition is invalid– All rows in the first table are joined to all rows in the second
table
To avoid a Cartesian product ,always include a valid join condition in a where clause
Equijoin
SELECT last_name, job_id, departments.department_id, department_nameFROM employees , departments WHERE employees.department_id = departments.department_id
SELECT last_name, job_id, departments.department_id, department_nameFROM employees , departments WHERE employees.department_id = departments.department_id
Table Aliases
SELECT e.last_name,e.job_id, d.department_id, d.department_nameFROM employees e, departments dWHERE e.department_id = d.department_id
SELECT e.last_name,e.job_id, d.department_id, d.department_nameFROM employees e, departments dWHERE e.department_id = d.department_id
Non-Equijoin
SELECT e.ename,e.sal,s.grade,s.losal,s.hisalFROM emp e,salgrade sWHERE e.sal BETWEEN s.losal AND s.hisal;
SELECT e.ename,e.sal,s.grade,s.losal,s.hisalFROM emp e,salgrade sWHERE e.sal BETWEEN s.losal AND s.hisal;
Outer Join
Employees Departments
SQL
Outer Join
SELECT e.first_name,d.department_name,d.department_idFROM departments d,employees eWHERE d.department_id=e.department_id(+)
SELECT e.first_name,d.department_name,d.department_idFROM departments d,employees eWHERE d.department_id=e.department_id(+)
SELECT e.first_name,d.department_name,d.department_idFROM departments d left outer join employees eON d.department_id=e.department_id
SELECT e.first_name,d.department_name,d.department_idFROM departments d left outer join employees eON d.department_id=e.department_id
Standard SQL
Oracle SQL
Self Join
Employees(worker) Employees(manager)
SQL
Self Join
SELECT w.last_name worker , m.last_name managerFROM employees w, employees mWHERE w.manager_id = m.employee_idAND w.last_name LIKE 'R%'
SELECT w.last_name worker , m.last_name managerFROM employees w, employees mWHERE w.manager_id = m.employee_idAND w.last_name LIKE 'R%'
Group Functions
Group function operate on sets of rows to give on result per group
Group function appear in both SELECT lists and HAVING clauses
The GROUP by clause in the SELECT statement divides rows into smaller groups
The HAVING clause restricts result groups
Group Functions
AVG COUNT MAX MIN STDDEV SUM VARIANCE
GROUP BY and HAVING in the SELECT statement
Group Functions (example)
SELECT count(*) FROM employees
SELECT count(*) FROM employees
Group Function (example)
SELECT job_id,SUM(SALARY),AVG(SALARY)FROM employeesGROUP BY job_idHAVING SUM(salary) > 20000ORDER BY SUM(salary)
SELECT job_id,SUM(SALARY),AVG(SALARY)FROM employeesGROUP BY job_idHAVING SUM(salary) > 20000ORDER BY SUM(salary)
Subquery
Subquery is a SELECT statement embedded in a clause of another SQL statement
SELECT ...
FROM ...
WHERE
SELECT ...
FROM ...
WHERE (SELECT ... FROM ... WHERE
MainQuery
Subquery
Subquery (example)
SELECT last_name,email,job_idFROM employeesWHERE department_id IN(SELECT department_id FROM departments WHERE location_id=1700)AND hire_date < '01-JAN-1994'
SELECT last_name,email,job_idFROM employeesWHERE department_id IN(SELECT department_id FROM departments WHERE location_id=1700)AND hire_date < '01-JAN-1994'
SQL Convention
SELECT DISTINCTfn.dept_id dept_id,fcoam.dp_acc_id acc_id,fn.cat,fn.sub_cat,fn.amount
FROM FET_ABM_FA_NBV fn,FET_ABM_FA_DP_RATE_MAP fdr,FET_ABM_FA_COC_ACC_MAP fcoam
WHERE fn.cat = fdr.catAND fn.sub_cat = fdr.sub_catAND fn.cat = fcoam.catAND fn.sub_cat || '-NON NETWORK' = fcoam.sub_cat AND fdr.cat_noNOT IN (1,2,3,4);
SELECT DISTINCTfn.dept_id dept_id,fcoam.dp_acc_id acc_id,fn.cat,fn.sub_cat,fn.amount
FROM FET_ABM_FA_NBV fn,FET_ABM_FA_DP_RATE_MAP fdr,FET_ABM_FA_COC_ACC_MAP fcoam
WHERE fn.cat = fdr.catAND fn.sub_cat = fdr.sub_catAND fn.cat = fcoam.catAND fn.sub_cat || '-NON NETWORK' = fcoam.sub_cat AND fdr.cat_noNOT IN (1,2,3,4);
Table name alias
UpperCase & Left Alignment
Exercise 4
由於 Chen (Last Name) 表現優異 , 董事長決定親自表揚 , 請找出他的工作地點 (City)
在銷售 (Sales) 部門 , 每月員工薪資支出是多少 ( 請列出部門名稱及薪資支出 )
請用計算薪資大於全公司平均薪資的員工數 請列出平均薪資大於全公司平均薪資的部門
( 列出部門名稱)
DAY 2
ERD
Data Models
Model of systemin client’s mind
Entity model
Table model of entity model
Database Server
Table on disk
Create Table Model
Step1:Map Entities to Tables Step2:Map the Attributes to Columns Step3:Map the Unique Identifiers to Primary Keys Step4:Map Relationships to Foreign Keys
Table Instance Chart
Column Name Data Type Key Type Fk Table Null
department_id Number(4) PK1 N
department_name Varchar2(30) N
manager_id Number(6) FK1 employees.emp_id
Y
location_id Number(4) FK2 location.location_id
Y
DEPARTMENTS Table
Creating Tables
Database objects
Object Description
Table Basic unit of storage composed of rows and columns
View Logically represents subsets of data from one or more tables
Sequence Generate primary key values
Index Improves the performance of some queries
Synonym Alternate name for an object
Program Unit Procedure, function or package of SQL and PL/SQL statement
Datatypes
Datatype Description
VARCHAR2(size) Variable length character value ,max 4000 bytes
CHAR(size) Fixed length character value, max 2000 bytes
NUMBER(precision,scale)
Number Values
DATE Date & Time values, January 1, 4712 BC to
December 31, 9999 AD.
CLOB Character large object, max 4Gb
BLOB Binary large object, max 4Gb
Number Type
Data Integrity Constraints
Constraint Description
NOT NULL Specifies that this may not contain a null value
UNIQUE Specifies a column or combination of columns whose values must be unique for all rows in the table.
PRIMARY KEY Uniquely identifies each row of the table.
FOREIGN KEY Establishes and enforces a foreign key relationship
between the column and a column of the referenced
table.
CHECK Specifies a condition that must be true.
Creating Table (example)
Creating Table (example)
Create Table (example)
Data Dictionary ( I )
Create when database is created Updated and maintained by the Oracle Server Information stored in the data dictionary
– Names of Oracle Server user– Privileges granted to users– Database object names– Table constraints– Auditing Information
Data Dictionary (II)
Four classes of views (prefixes)– USER Objects owned by user– ALL Objects user has access rights– DBA All database objects– V$ Performance Information
Checking Constraint on a Table
SELECT CONSTRAINT_NAME,COLUMN_NAME,POSITIONFROM USER_CONS_COLUMNSWHERE TABLE_NAME =‘DEPARTMENTS'ORDER BY CONSTRAINT_NAME,POSITION
SELECT CONSTRAINT_NAME,COLUMN_NAME,POSITIONFROM USER_CONS_COLUMNSWHERE TABLE_NAME =‘DEPARTMENTS'ORDER BY CONSTRAINT_NAME,POSITION
Manipulating Data
DML & Transaction Control
Command Description
INSERT Add new rows to the table
UPDATE Modify existing rows in the table
DELETE Remove existing rows in the table
COMMIT Make all pending changes permanent
SAVEPOINT Allows a rollback to that savepoint maker
ROLLBACK Discards all pending data changes
Adding a New Row to a Table
INSERT INTO DEPARTMENTS (department_id,department_name,manager_id,location_id)VALUES (271,'Outsoucing',NULL,1700);
INSERT INTO DEPARTMENTS (department_id,department_name,manager_id,location_id)VALUES (271,'Outsoucing',NULL,1700);
INSERT INTO table [ ( column [ , column ...] ) ]VALUES ( value [, value ....] );
INSERT INTO table [ ( column [ , column ...] ) ]VALUES ( value [, value ....] );
Example
Syntax
Copy Rows from Another Table
Write INSERT command with subquery Do not use VALUES clause Match the number of columns in the INSERT
clause to those in subquery
INSERT INTO JOB_HISTORY (employee_id,start_date,end_date,job_id,department_id)SELECT employee_id,hire_date,SYSDATE,job_id,department_idFROM employeesWHERE job_id=‘SH_CLERK’
INSERT INTO JOB_HISTORY (employee_id,start_date,end_date,job_id,department_id)SELECT employee_id,hire_date,SYSDATE,job_id,department_idFROM employeesWHERE job_id=‘SH_CLERK’
Update Rows in a Tables
UPDATE employeesSET salary = salary * 1.05WHERE job_id ='SA_REP'
UPDATE employeesSET salary = salary * 1.05WHERE job_id ='SA_REP'
Example
UPDATE tableSET column = value , [column = value ][ WHERE condition ] ;
UPDATE tableSET column = value , [column = value ][ WHERE condition ] ;
Syntax
Deleting Rows from a Table
DELETE employeesWHERE job_id like ‘IT%’
DELETE employeesWHERE job_id like ‘IT%’
Example
DELETE table[ WHERE condition ] ;
DELETE table[ WHERE condition ] ;
Syntax
Data Consistency (Transaction)
Atomicity ( 不可分割性 ) Durability ( 持續性 )
COMMIT and ROLLBACK
Ensure data consistency Preview data changes before making changes
permanent Group logically related operations
State of the Data Before COMMIT or ROLLBACK
The previous state of the data can be recovered The current user can review the results of the DML
operations by using the SELECT statement Other users cannot view the results of the DML
statements by the current user The affected rows are locked; other users cannot
change the data within the affected rows
State of the Data After COMMIT
The previous data is permanently lost All users can view the results Locks on the affected rows are released
Committing Data (example)
SQL> INSERT INTO DEPARTMENTS 2 (department_id,department_name,manager_id,location_id) 3 VALUES (271,'Outsoucing',NULL,1700);
1 row created.
SQL> COMMIT;
Commit complete.
SQL> INSERT INTO DEPARTMENTS 2 (department_id,department_name,manager_id,location_id) 3 VALUES (271,'Outsoucing',NULL,1700);
1 row created.
SQL> COMMIT;
Commit complete.
State of the Data After ROLLBACK
Data change are undone Previous state of the data restored Locks on the affected rows are released
Rollback Data (example)
SQL> DELETE JOB_HISTORY;
10 rows deleted.
SQL> SELECT COUNT(*) FROM JOB_HISTORY;
COUNT(*)---------- 0
SQL> ROLLBACK;
Rollback complete.
SQL> SELECT COUNT(*) FROM JOB_HISTORY;
COUNT(*)---------- 10
SQL> DELETE JOB_HISTORY;
10 rows deleted.
SQL> SELECT COUNT(*) FROM JOB_HISTORY;
COUNT(*)---------- 0
SQL> ROLLBACK;
Rollback complete.
SQL> SELECT COUNT(*) FROM JOB_HISTORY;
COUNT(*)---------- 10
Creating Sequences
CREATE SEQUENCE sequence_name [INCREMENT BY n ] [START WITH n ] [ {MAXVALUE n | NOMAXVALUE } ] [ {MINVALUE n | NOMMINVALUE } ] [ { CYCLE | NOCYCLE } ] [ { CACHE n | NOCACHE } ]
CREATE SEQUENCE sequence_name [INCREMENT BY n ] [START WITH n ] [ {MAXVALUE n | NOMAXVALUE } ] [ {MINVALUE n | NOMMINVALUE } ] [ { CYCLE | NOCYCLE } ] [ { CACHE n | NOCACHE } ]
Syntax
Creating Sequences
CREATE SEQUENCE S1 INCREMENT BY 2START WITH 5MINVALUE 1MAXVALUE 10NOCACHECYCLE
CREATE SEQUENCE S1 INCREMENT BY 2START WITH 5MINVALUE 1MAXVALUE 10NOCACHECYCLE
Example
5 8 1 4 7 10 1 4 7 10
What Is a View ?
Advantages of Views
Restrict database access Simplify queries Present the data in a different perspective from that
of the base table Isolate applications from changes in definitions of
base tables Provide groups of users access to data according to
their particular criteria.
Creating a View
The subquery can contain complex SELECT syntax The subquery cannot an ORDER BY clause
CREATE VIEW view_name[ ( alias , [ alias ]...)]AS subquery[WITH CHECK OPTION [CONSTRAINT constraint]][WITH READ ONLY]
CREATE VIEW view_name[ ( alias , [ alias ]...)]AS subquery[WITH CHECK OPTION [CONSTRAINT constraint]][WITH READ ONLY]
Syntax
Creating a View (example)
Create the STAFF_60_V,which contain employee number, last name ,job ,manager’s employee number and department id for the employees in department 60
CREATE VIEW STAFF_60_V(employee_id,last_name,job_id,manager_id,department_id)ASSELECT employee_id,last_name,job_id,manager_id,department_idFROM employeesWHERE department_id= 60
CREATE VIEW STAFF_60_V(employee_id,last_name,job_id,manager_id,department_id)ASSELECT employee_id,last_name,job_id,manager_id,department_idFROM employeesWHERE department_id= 60
Creating a Complex View (example)
Creating a complex view that contain group function to display values from two tables
CREATE VIEW DEPT_SALARY_VIEWASSELECT d.department_name,SUM(salary) sum_salary ,MIN(SALARY) min_salary,MAX(SALARY) max_salaryFROM EMPLOYEES e,DEPARTMENTS dWHERE e.department_id = d.department_idGROUP BY d.department_name
CREATE VIEW DEPT_SALARY_VIEWASSELECT d.department_name,SUM(salary) sum_salary ,MIN(SALARY) min_salary,MAX(SALARY) max_salaryFROM EMPLOYEES e,DEPARTMENTS dWHERE e.department_id = d.department_idGROUP BY d.department_name
Exercise 5
Create View 列出員工姓名及主管姓名 (last name & first name)
由於業務部門績效良好 , 董事長決定全部加薪 10%, 請更改他們的薪資 , 並列出薪資超出該職務( job_id) 上限的人員
公司決定自即日起將 IT 工作外包 , 請將 IT 人員自 employees Table 中移除,並將相關資料放至 job_history
What Is a Index ?
Database Object Each index is composed of column values and
pointers (or ROWID) Indexes is maintained and used by RDBMS
Index Type
By constraint– Unique– Non-unique
By constitution– Single Column– Concatenated or Composite
How are Indexes Created ?
Automatically– A unique index are created when you define PRIMARY KE
Y or UNIQUE KEY constraint in a table defination
Manually– CREATE INDEX command
Creating and Index
CREATE [UNIQUE ] INDEX index_name ON table (column [,column]...)
CREATE [UNIQUE ] INDEX index_name ON table (column [,column]...)
Syntax
CREATE UNIQUE INDEX job_id_pk ON jobs (job_id) ;
CREATE UNIQUE INDEX job_id_pk ON jobs (job_id) ;
Example
Guideline to Create an Index
The columns are used frequently in WHERE clause or in join condition
The column contain a wide range of values The column contain a large number of null value
Confirming Indexes
USER_INDEXES USER_IND_COLUMNS
DAY 3
PL/SQL
PL/SQL Block Structure
DECLARE (Optional)– Variables,constants,cursors,user-defined exception
BEGIN (Mandatory)– SQL Statements– PL/SQL Control statement
EXCEPTION (Optional)– Action to perform when errors occurs
END; (Mandatory)
Example PL/SQL Block
DECLAREEmp_name VARCHAR2(10);Emp_number INTEGER;
Empno_out_of_range EXCEPTION;BEGIN
Emp_number := 10001;IF Emp_number > 9999 OR Emp_number < 1000 THENRAISE Empno_out_of_range;ELSESELECT Ename INTO Emp_name FROM Emp_tabWHERE Empno = Emp_number;DBMS_OUTPUT.PUT_LINE('Employee name is' || Emp_name);END IF;
EXCEPTIONWHEN Empno_out_of_range THENDBMS_OUTPUT.PUT_LINE('Employee number' || Emp_number ||'is out of range.');
END;
Block Types
Anonymous Procedure
[DECLARE]
BEGIN
-- Statement[EXCEPTION]
END;
[DECLARE]
BEGIN
-- Statement[EXCEPTION]
END;
PROCEDURE nameIS
BEGIN
-- Statement[EXCEPTION]
END;
PROCEDURE nameIS
BEGIN
-- Statement[EXCEPTION]
END;
Function
FUNCTION nameRETURN datatypeIS
BEGIN
-- StatementRETURN value;[EXCEPTION]
END;
FUNCTION nameRETURN datatypeIS
BEGIN
-- StatementRETURN value;[EXCEPTION]
END;
Program Constructs
Stored Procedure and Function (Package) Application Procedure and Function (Package) Database Trigger Application Trigger (Form ,Report) Anonymous Block
Declare Variables
PL/SQL variables– Scalar– Composite– Reference (Pointer)– LOB (Large Objects)
Built-in Datatypes Quick Ref.
Declaring PL/SQL Variable
identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr ];
identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr ];
Declarev_adjust_amount NUMBER NOT NULL:= 0;v_nbv_amount NUMBER := 0;v_dis_nbv_amount NUMBER := 0;
Declarev_adjust_amount NUMBER NOT NULL:= 0;v_nbv_amount NUMBER := 0;v_dis_nbv_amount NUMBER := 0;
Syntax
Example
Declaring Variables with the %TYPE Attribute
Example
…DECLAREv_ename emp.ename%TYPE;v_balance NUMBER(7,2);…
…DECLAREv_ename emp.ename%TYPE;v_balance NUMBER(7,2);…
Base Scalar Datatypes
VARCHAR2(maximun_length) NUMBER[(precision,scale)] DATE CHAR(maximun_length) ………
Code Naming Convention
Identifier Naming Conversion Example
Variable v_name v_sal
Constant c_name c_company_name
Cursor name_cursor emp_cursor
Exception e_name e_too_many
Table type name_table_type amount_table_type
Table name_table order_total_table
Record Type name_record_type emp_record_type
Record name_record customer_record
SELECT statement in PL/SQL
SELECT select_listINTO { variable_name [,variable_name]....
| record_name }FROM tableWHERE condition;
SELECT select_listINTO { variable_name [,variable_name]....
| record_name }FROM tableWHERE condition;
Retrieve data from the database with SELECT
Syntax
SELECT statement in PL/SQL
INTO clause Queries Must Return One and Only One Row
– NO_DATA_FOUND– TOO_MANY_ROWS
Simple PL/SQL Block
DECLAREv_deptno NUMBER(2);v_loc VARCHAR2(15);
BEGINSELECT deptno
,locINTO v_deptno
,v_locFROM deptWHERE dname='SALES';
DBMS_OUTPUT.PUT_LINE(TO_CHAR(v_deptno)); DBMS_OUTPUT.PUT_LINE(v_loc);END;
DECLAREv_deptno NUMBER(2);v_loc VARCHAR2(15);
BEGINSELECT deptno
,locINTO v_deptno
,v_locFROM deptWHERE dname='SALES';
DBMS_OUTPUT.PUT_LINE(TO_CHAR(v_deptno)); DBMS_OUTPUT.PUT_LINE(v_loc);END;
Exercise 6
1. Create a PL/SQL block that selects the maximum department number in the DEPT table and print the results to the screen.
2. Modified the PL/SQL block you created in previous exercise to insert a new department into DEPT table
– add 10 to the maxinum department number– Use SQL*Plus substitution variable for the department name– Leave the location null
Determining Variable Scope
DECLARE v_sal NUMBER(7,2) := 6000; v_comm NUMBER(7,2) := v_sal * 0.2; v_message VARCHAR2(255) := 'eligible for commission';BEGIN DECLARE v_sal NUMBER(7,2) := 50000; v_comm NUMBER(7,2) := 0; v_total_comp NUMBER(7,2) := v_sal + v_comm; BEGIN v_message := 'CLERK not' || v_message; END; v_message := 'SALESMAN' || v_message;END;
DECLARE v_sal NUMBER(7,2) := 6000; v_comm NUMBER(7,2) := v_sal * 0.2; v_message VARCHAR2(255) := 'eligible for commission';BEGIN DECLARE v_sal NUMBER(7,2) := 50000; v_comm NUMBER(7,2) := 0; v_total_comp NUMBER(7,2) := v_sal + v_comm; BEGIN v_message := 'CLERK not' || v_message; END; v_message := 'SALESMAN' || v_message;END;
Commenting Code
Prefix single-line comments with two dash(--) Place multi-line comments between the symbols
/* and */
... v_sal NUMBER(7,2);BEGIN /* Compute the annual salary based on the monthly salary input from the user */ v_sal := &p_monthly_sal * 12;END; -- This is the end of the block
... v_sal NUMBER(7,2);BEGIN /* Compute the annual salary based on the monthly salary input from the user */ v_sal := &p_monthly_sal * 12;END; -- This is the end of the block
Writing Control Structures
IF statement LOOP GOTO
IF Statement
Conditional IF statements– IF-THEN-END IF– IF-THEN-ELSE-END IF– IF-THEN-ELSIF-END IF
Simple IF Statement
...IF v_ename = 'MILLER' THENTHEN v_job := 'SALESMAN'; v_new_comn := sal * 0.2;ELSIF v_ename = 'JONES' THEN v_job := 'MANAGER'; v_new_comn := sal * 0.2;ELSE ...........END IF;
...IF v_ename = 'MILLER' THENTHEN v_job := 'SALESMAN'; v_new_comn := sal * 0.2;ELSIF v_ename = 'JONES' THEN v_job := 'MANAGER'; v_new_comn := sal * 0.2;ELSE ...........END IF;
Basic Loop
DECLARE v_ordid item.ordid%TYPE := 601; v_counter NUMBER(2) := 1;BEGIN LOOP INSERT INTO item(ordid,itemid) VALUES (v_ordid,v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP;END;
DECLARE v_ordid item.ordid%TYPE := 601; v_counter NUMBER(2) := 1;BEGIN LOOP INSERT INTO item(ordid,itemid) VALUES (v_ordid,v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP;END;
FOR loop
BEGIN FOR i IN 1..10 LOOP INSERT INTO item(ordid,itemid) VALUES (i,v_counter); END LOOP;END;
BEGIN FOR i IN 1..10 LOOP INSERT INTO item(ordid,itemid) VALUES (i,v_counter); END LOOP;END;
Do not declare the counter,it is declared implicitly
WHILE Loop
DECLARE v_ordid item.ordid%TYPE := 601; v_counter NUMBER(2) := 1;BEGIN
WHILE v_counter <= 10 LOOP INSERT INTO item(ordid,itemid) VALUES (v_ordid,v_counter); v_counter := v_counter + 1; END LOOP;END;
DECLARE v_ordid item.ordid%TYPE := 601; v_counter NUMBER(2) := 1;BEGIN
WHILE v_counter <= 10 LOOP INSERT INTO item(ordid,itemid) VALUES (v_ordid,v_counter); v_counter := v_counter + 1; END LOOP;END; exit
Nested Loop and Labels
DECLARE v_ordid item.ordid%TYPE := 601; v_counter NUMBER(2) := 1; v_dummy NUMBER;BEGIN LOOP INSERT INTO item(ordid,itemid) VALUES (v_ordid,v_counter); v_counter := v_counter + 1; IF v_counter > 10 THEN GOTO end_loop; END IF; END LOOP;<<end_loop>>v_dummy := 1;END;
DECLARE v_ordid item.ordid%TYPE := 601; v_counter NUMBER(2) := 1; v_dummy NUMBER;BEGIN LOOP INSERT INTO item(ordid,itemid) VALUES (v_ordid,v_counter); v_counter := v_counter + 1; IF v_counter > 10 THEN GOTO end_loop; END IF; END LOOP;<<end_loop>>v_dummy := 1;END;
Practice 7
CREATE TABLE MESSAGES(RESULT VARCHAR2(100));
– Insert the number 1 to 10 ,excluding 6 and 8
– Select from the MESSAGES table to verify that your PL/SQL block work
Add a new column called STARS of datatype VARCHAR2 and length 20 ,to the EMP table ,Update STARS column as the following result
Composite Datatypes
PL/SQL RECORDS PL/SQL TABLES
PL/SQL Record
DECLARETYPE emp_record_type IS RECORD(ename VARCHAR2(10),
job VARCHAR2(9), sal NUMBER(7,2));
emp_record emp_record_type;BEGINEND;
DECLARETYPE emp_record_type IS RECORD(ename VARCHAR2(10),
job VARCHAR2(9), sal NUMBER(7,2));
emp_record emp_record_type;BEGINEND;
The %ROWTYPE Attribute
DECLARE emp_record emp%ROWTYPE;BEGIN ….END;
DECLARE emp_record emp%ROWTYPE;BEGIN ….END;
PL/SQL Tables
TYPE ename_table_type IS TABLE of emp.ename%TYPE INDEX BY BINARY_INTEGER;
ename_table ename_table_type;
TYPE ename_table_type IS TABLE of emp.ename%TYPE INDEX BY BINARY_INTEGER;
ename_table ename_table_type;
Writing Explicit Cursor
About Cursors
– Implicit Cursors :Declared for all DML and PL/SQL SELECT statement
– Explicit Cursors:Declared and named by the programmer
Every SQL Statement executed by the Oracle Server has an indifidual cursor associated with it
Explicit Cursor Function
7369 SMITH CLERK7499 ALLEN SALESMAN7521 WARD SALESMAN7566 JONES MANAGER7654 MARTIN SALESMAN7698 BLAKE MANAGER
cursor Current row
Controlling Explicit Cursor
DECLARE FETCH CLOSEOPEN EMPTY?
NO
YES
Explicit Cursor example
DECLARE CURSOR emp_cur IS SELECT ename,job FROM EMP; emp_record emp_cur%ROWTYPE;BEGIN OPEN emp_cur; LOOP FETCH emp_cur INTO emp_record; EXIT WHEN emp_cur%NOTFOUND; END LOOP; CLOSE emp_cur;END;
DECLARE CURSOR emp_cur IS SELECT ename,job FROM EMP; emp_record emp_cur%ROWTYPE;BEGIN OPEN emp_cur; LOOP FETCH emp_cur INTO emp_record; EXIT WHEN emp_cur%NOTFOUND; END LOOP; CLOSE emp_cur;END;
Explicit Cursor Attribute
Attribute Type Description
%ISOPEN Boolean Evaluates to TRUE if the cursor is open
%NOTFOUND Boolean Evaluates to TRUE if the most recent fetch does not return a row
%FOUND Boolean Evaluates to TRUE if the most recent fetch returns a row
%ROWCOUNT Number Evaluates to the total number of rows returned so far
Cursor FOR Loops
DECLARE CURSOR emp_cur IS SELECT ename,job FROM EMP;BEGIN FOR emp_record IN emp_cur LOOP -- implicit open and implicit fetch occur IF emp_record.deptno = 30 THEN ......... END IF; END LOOP; -- implicit close occursEND;
DECLARE CURSOR emp_cur IS SELECT ename,job FROM EMP;BEGIN FOR emp_record IN emp_cur LOOP -- implicit open and implicit fetch occur IF emp_record.deptno = 30 THEN ......... END IF; END LOOP; -- implicit close occursEND;
Cursors with Parameters
DECLARE CURSOR emp_cursor (p_deptno NUMBER,p_job VARCHAR2) IS SELECT empno,ename FROM emp WHERE deptno = p_deptno AND job = p_job;BEGIN OPEN emp_cursor (10,'CLERK')......
DECLARE CURSOR emp_cursor (p_deptno NUMBER,p_job VARCHAR2) IS SELECT empno,ename FROM emp WHERE deptno = p_deptno AND job = p_job;BEGIN OPEN emp_cursor (10,'CLERK')......
Pass the department number and job title to the WHERE clause do not give them sizes
Cursor with Parameters
DECLARE CURSOR emp_cursor (p_deptno NUMBER,p_job VARCHAR2) IS SELECT empno,ename FROM emp WHERE deptno = p_deptno AND job = p_job;BEGIN FOR emp_record IN emp_cursor(10,'CLERK') LOOP ..... END LOOP;
DECLARE CURSOR emp_cursor (p_deptno NUMBER,p_job VARCHAR2) IS SELECT empno,ename FROM emp WHERE deptno = p_deptno AND job = p_job;BEGIN FOR emp_record IN emp_cursor(10,'CLERK') LOOP ..... END LOOP;
You can pass parameters to the cursor used in a cursor FOR loop
The FOR UPDATE Clause
DECLARE CURSOR emp_cursor IS SELECT empno,ename FROM emp WHERE deptno = 30 FOR UPDATE [ OF sal ] NOWAIT;
DECLARE CURSOR emp_cursor IS SELECT empno,ename FROM emp WHERE deptno = 30 FOR UPDATE [ OF sal ] NOWAIT;
Optional
The FOR UPDATE Clause
Lock the affected rows when the cursor is opened You should not commit across fetched from a explicit curs
or if FOR UPDATE is used(because the Oracle Server releases locks at the end fo the transaction)
FOR UPDATE clause is the last clause in a select statement
The WHERE CURRENT OF Clause
Use cursors to update or delete the current row Include the FOR UPDATE clause in the cursor query to lock the rows
first Use the WHERE CURRENT OF clause to reference the current row
from an explicit cursor
Syntax:
WHERE CURRENT OF cursor;WHERE CURRENT OF cursor;
The WHERE CURRENT OF Clause (example)
DECLARE CURSOR sal_cursor IS SELECT sal FROM emp WHERE deptno = 30 FOR UPDATE OF sal NOWAIT;BEGIN FOR emp_record IN sal_cursor LOOP
UPDATE empSET sal = sal * 1.10WHERE CURRENT OF sal_cursor;
END LOOP;END;
DECLARE CURSOR sal_cursor IS SELECT sal FROM emp WHERE deptno = 30 FOR UPDATE OF sal NOWAIT;BEGIN FOR emp_record IN sal_cursor LOOP
UPDATE empSET sal = sal * 1.10WHERE CURRENT OF sal_cursor;
END LOOP;END;
Summary (Cursor)
Cursor type:– Implicit cursors:Used for all DML statements and single-row querie
s– Explicit cursors:Used for queries of zero,one,or more rows
You can manipulate explicit cursors You can evaluate the cursor status by using cursor attributes You can use cursor FOR loops
Handling Exceptions
Handling Exceptions with PL/SQL
What is an exception– In PL/SQL, a warning or error condition is called an exception.
How is it raised?– An Oracle error occurs– You raise it explicitly
How do you handle it?– Trap it with a handle it– Propagate it to the calling environment
Handling Exception
Trap the exception Propagate the exception
DECLARE
BEGIN
EXCEPTION
END;
exception is raised
exception is trapped
DECLARE
BEGIN
EXCEPTION
END;
exception is raised
exception is not trapped
Excepiton propagates to calling environment
Exception Types
Predefined Oracle Server Non-predefined Oracle Server User-defined
Implicitly raised
Explicitly raised
Trapping Exceptions Guildlines
WHEN OTHERS is the last cluase EXCEPTION keyword start exception handling section Serveral exception handlers are allowed Only one handler is processed before leaving the block
Predefined Exception (example)
BEGIN EXCEPTION WHEN NO_DATA_FOUND THEN statement1; statement2; WHEN TOO_MANY_ROWS THEN statement1; statement2; WHEN OTHERS THEN statement1; statement2; END;
BEGIN EXCEPTION WHEN NO_DATA_FOUND THEN statement1; statement2; WHEN TOO_MANY_ROWS THEN statement1; statement2; WHEN OTHERS THEN statement1; statement2; END;
Predefined Oracle Server Errors
Using SQLCODE & SQLERRM
User-Defined Exception
How Exception Propagate
How Exception Propagate
How Exception Propagate
Practice 8
Write a PL/SQL block to select the name of the employee with a given salary,insert the result in MESSAGES table
RESULT--------------------------------------------------------------------------------SMITH -800More than one employee with a salary of 3000No employee with a salary 6000
Stored Procedures & Functions
Create Stored Procedure (example)
CREATE OR REPLACE PROCEDURE raise_salary (emp_id INTEGER, amount NUMBER) IScurrent_salary NUMBER;salary_missing EXCEPTION;
BEGINSELECT sal INTO current_salary FROM empWHERE empno = emp_id;IF current_salary IS NULL THENRAISE salary_missing;ELSEUPDATE emp SET sal = sal + amountWHERE empno = emp_id;END IF;
EXCEPTIONWHEN NO_DATA_FOUND THENINSERT INTO emp_audit VALUES (emp_id, 'No such number');WHEN salary_missing THENINSERT INTO emp_audit VALUES (emp_id, 'Salary is null');
END raise_salary;
CREATE OR REPLACE PROCEDURE raise_salary (emp_id INTEGER, amount NUMBER) IScurrent_salary NUMBER;salary_missing EXCEPTION;
BEGINSELECT sal INTO current_salary FROM empWHERE empno = emp_id;IF current_salary IS NULL THENRAISE salary_missing;ELSEUPDATE emp SET sal = sal + amountWHERE empno = emp_id;END IF;
EXCEPTIONWHEN NO_DATA_FOUND THENINSERT INTO emp_audit VALUES (emp_id, 'No such number');WHEN salary_missing THENINSERT INTO emp_audit VALUES (emp_id, 'Salary is null');
END raise_salary;
Execute Stored Procedure
EXEC RAISE_SALARY(7900,300)EXEC RAISE_SALARY(7900,300)
BEGIN RAISE_SALARY(7900,300)END;
BEGIN RAISE_SALARY(7900,300)END;
BEGIN RAISE_SALARY (emp_id => 7900 amount => 300 );END;
BEGIN RAISE_SALARY (emp_id => 7900 amount => 300 );END;
Create Stored Function (example)
CREATE OR REPLACE FUNCTION emp_sal_query (i_empno NUMBER) RETURN NUMBERIS v_sal NUMBER;BEGIN
SELECT sal INTO v_salFROM empWHERE empno = i_empno;
RETURN v_sal;EXCEPTION
WHEN NO_DATA_FOUND THENRETURN NULL;
END emp_sal_query;
CREATE OR REPLACE FUNCTION emp_sal_query (i_empno NUMBER) RETURN NUMBERIS v_sal NUMBER;BEGIN
SELECT sal INTO v_salFROM empWHERE empno = i_empno;
RETURN v_sal;EXCEPTION
WHEN NO_DATA_FOUND THENRETURN NULL;
END emp_sal_query;
Execute Stored Function
SELECT emp_sal_query(7369) FROM dual;SELECT emp_sal_query(7369) FROM dual;
SELECT emp_sal_query(empno),ename FROM emp;SELECT emp_sal_query(empno),ename FROM emp;
DECLARE
v_sal NUMBER;
BEGIN
v_sal := emp_sal_query(7369) ;
DBMS_OUTPUT.PUT_LINE(TO_CHAR(v_sal));
END;
DECLARE
v_sal NUMBER;
BEGIN
v_sal := emp_sal_query(7369) ;
DBMS_OUTPUT.PUT_LINE(TO_CHAR(v_sal));
END;
Practice 9
SQL*Loader Overview
Discarded and Rejected Records
SQL*Loader Case Studies
$ORACLE_HOME/rdbms/demo/ulcase*.*
Recommendable
Oracle Essentials:Oracle 9i,Oracle8i & Oracle8– O’RELLY
Oracle Design – O’REILLY Oracle SQL High-Performance Tuning—Prentice Hal
l Oracle 資料庫管理實務—旗標 Oracle 9i Java 程式設計– 金禾