Presentation is loading. Please wait.

Presentation is loading. Please wait.

Oracle SQL introduction. 使用聲明 請尊重智慧財產權 本資料僅限高雄應用科技大學資管系教學使用 未經允許請勿擅自複製、散佈、使用.

Similar presentations


Presentation on theme: "Oracle SQL introduction. 使用聲明 請尊重智慧財產權 本資料僅限高雄應用科技大學資管系教學使用 未經允許請勿擅自複製、散佈、使用."— Presentation transcript:

1 Oracle SQL introduction

2 使用聲明 請尊重智慧財產權 本資料僅限高雄應用科技大學資管系教學使用 未經允許請勿擅自複製、散佈、使用

3 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

4 DAY 1

5 Terminology Instance (SGA + background process) Database (control file + data file + redo files) Tablespace Schema Object – Table,Index,Sequence,View,Package,Procedure,Function,C luster…etc

6 Database Structure Overview Control File Redo log Files Data Files Parameter File File Archived Log File Instance Database SGA SharedPool LibraryCache Data Dict. Cache DatabaseBufferCache Redo log Buffer SMON DBW0 PMON CKPT LGWR ARC0 UserProcess ServerProcess

7 Stages in Startup and ShutdownOPEN MOUNT NOMOUNT SHUTDOWN STARTUP SHUTDOWN

8 How to determine Database up or down ? (Windows)

9 How to determine Database up or down ? (UNIX)

10 Database & Tablespace

11 Tablespace & Database object

12 Oracle E-Business Suite Tablespace Design SYSTEM TEMP RBS FNDD FNDX GLD GLX OED OEX

13 Establishing Connections to Oracle Servers

14 How to determine Listener up or down?(Windows)

15 How to determine Listener up or down?(Unix)

16 Starting and using the Net Configuration Assistant

17 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)) )

18 SQL*Plus

19 Logging into Database 開始  程式集  Oracle 9i  Application Development  SQL Plus

20 Logging into Database

21 SQL*Plus Command Summary (I) @ & get edit execute host list /

22 SQL*Plus Command Summary (II) spool connect describe column set show all exit help

23 3rd Party Tools TOAD (Quest Software) SQL Navigator (Quest Software)

24 Exercise 1 Installation Oracle 9i Database Create Database Connect to Database by SQL* Net (using SQL* Plus) show user

25 Sample Schema Diagrams

26 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

27 SQL

28 Displaying Table Structure

29 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

30 Selecting All Columns, All Rows

31 Selecting Specific Columns

32 Arithmetic Expressions

33 Concatenation Operator

34 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 NULL

35 Conditions containing NULL

36 Conditions containing NULL (example)

37 NVL function Converts null to an actual value Datatype that can be used are date,character,and number Datatype must match – NVL(comm,0) – NVL(hiredate,’01-JAN-97’) – NVL(job,’Not Job Yet’)

38 NVL Function (example)

39 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 ])

40 Using the DECODE Function (example)

41 Built-in Function Quick Ref.

42 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;

43 Preventing the Selection of Duplicate Rows(example) SQL>SELECT JOB_ID 2FROM EMPLOYEES; JOB_ID -------------------- SA_MAN SA_REP SH_CLERK SQL>SELECT JOB_ID 2FROM EMPLOYEES; JOB_ID -------------------- SA_MAN SA_REP SH_CLERK Display All Rows SQL>SELECT DISTINCT JOB_ID 2FROM EMPLOYEES; JOB_ID -------------------- AC_ACCOUNT AC_MGR AD_ASST AD_PRES AD_VP FI_ACCOUNT FI_MGR HR_REP SQL>SELECT DISTINCT JOB_ID 2FROM EMPLOYEES; JOB_ID -------------------- AC_ACCOUNT AC_MGR AD_ASST AD_PRES AD_VP FI_ACCOUNT FI_MGR HR_REP Display Unique Rows Duplicate Rows

44 Limiting Selected Rows

45 Comparison and Logical Operations Logical comparison operators = > >= < <= SQL comparison operators – BETWEEN... AND – IN (list) – LIKE – IS NULL Logical operators – AND – OR – NOT

46 The WHERE Clause SELECT first_name,last_name,job_id FROM employees WHERE first_name = 'John‘; SELECT first_name,last_name,job_id FROM employees WHERE first_name = 'John‘; FIRST_NAME LAST_NAME JOB_ID --------------- ------------------------------ ---------------- John Chen FI_ACCOUNT John Seo ST_CLERK John Russell SA_MAN FIRST_NAME LAST_NAME JOB_ID --------------- ------------------------------ ---------------- John Chen FI_ACCOUNT John Seo ST_CLERK John Russell SA_MAN

47 Negating Expressions Logical Operators – != <> ^= SQL Operator – NOT BETWEEN... AND... – NOT IN – NOT LIKE – IS NOT NULL

48 The ORDER BY Clause

49 Exercise 2 Installing the Human Resources (HR) Schema 列出薪資超過 10000 之員工姓名, 受雇日期, 部門及薪資 列出所有銷售部門的員工編號, 姓名及薪資,, 並依受雇日期 做 sorting (descending)

50 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

51 RR Date Format

52 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

53 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

54 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

55 Date Function MONTHS_BETWEEN(date1,date2) ADD_MONTHS(date,n) NEXT_DAY(date,’char’) LAST_DAY(date) ROUND(date,’fmt’) TRUNC(date,’fmt’)

56 Exercise 3 列出年資超過 3 年的員工姓名, 薪資, 受雇日期

57 Displaying Data from Multiple Tables

58 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

59 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.column FROM table1,table2 WHERE table1.column1=table2.column2; SELECT table1.column,table.column FROM table1,table2 WHERE table1.column1=table2.column2;

60 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

61 Equijoin SELECT last_name, job_id, departments.department_id, department_name FROM employees, departments WHERE employees.department_id = departments.department_id SELECT last_name, job_id, departments.department_id, department_name FROM employees, departments WHERE employees.department_id = departments.department_id

62 Table Aliases SELECT e.last_name,e.job_id, d.department_id, d.department_name FROM employees e, departments d WHERE e.department_id = d.department_id SELECT e.last_name,e.job_id, d.department_id, d.department_name FROM employees e, departments d WHERE e.department_id = d.department_id

63 Non-Equijoin SELECT e.ename,e.sal,s.grade,s.losal,s.hisal FROM emp e,salgrade s WHERE e.sal BETWEEN s.losal AND s.hisal; SELECT e.ename,e.sal,s.grade,s.losal,s.hisal FROM emp e,salgrade s WHERE e.sal BETWEEN s.losal AND s.hisal;

64 Outer Join Employees Departments SQL

65 Outer Join SELECT e.first_name,d.department_name,d.department_id FROM departments d,employees e WHERE d.department_id=e.department_id(+) SELECT e.first_name,d.department_name,d.department_id FROM departments d,employees e WHERE d.department_id=e.department_id(+) SELECT e.first_name,d.department_name,d.department_id FROM departments d left outer join employees e ON d.department_id=e.department_id SELECT e.first_name,d.department_name,d.department_id FROM departments d left outer join employees e ON d.department_id=e.department_id Standard SQL Oracle SQL

66 Self Join Employees(worker) Employees(manager) SQL

67 Self Join SELECT w.last_name worker, m.last_name manager FROM employees w, employees m WHERE w.manager_id = m.employee_id AND w.last_name LIKE 'R%' SELECT w.last_name worker, m.last_name manager FROM employees w, employees m WHERE w.manager_id = m.employee_id AND w.last_name LIKE 'R%'

68 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

69 Group Functions AVG COUNT MAX MIN STDDEV SUM VARIANCE

70 GROUP BY and HAVING in the SELECT statement

71 Group Functions (example) SELECT count(*) FROM employees SELECT count(*) FROM employees

72 Group Function (example) SELECT job_id,SUM(SALARY),AVG(SALARY) FROM employees GROUP BY job_id HAVING SUM(salary) > 20000 ORDER BY SUM(salary) SELECT job_id,SUM(SALARY),AVG(SALARY) FROM employees GROUP BY job_id HAVING SUM(salary) > 20000 ORDER BY SUM(salary)

73 Subquery Subquery is a SELECT statement embedded in a clause of another SQL statement SELECT... FROM... WHERE SELECT... FROM... WHERE (SELECT... FROM... WHERE Main Query Subquery

74 Subquery (example) SELECT last_name,email,job_id FROM employees WHERE department_id IN(SELECT department_id FROM departments WHERE location_id=1700) AND hire_date < '01-JAN-1994' SELECT last_name,email,job_id FROM employees WHERE department_id IN(SELECT department_id FROM departments WHERE location_id=1700) AND hire_date < '01-JAN-1994'

75 SQL Convention SELECT DISTINCT fn.dept_iddept_id,fcoam.dp_acc_idacc_id,fn.cat,fn.sub_cat,fn.amount FROMFET_ABM_FA_NBV fn, FET_ABM_FA_DP_RATE_MAP fdr, FET_ABM_FA_COC_ACC_MAP fcoam WHERE fn.cat= fdr.cat ANDfn.sub_cat = fdr.sub_cat ANDfn.cat= fcoam.cat ANDfn.sub_cat || '-NON NETWORK'= fcoam.sub_cat AND fdr.cat_noNOT IN (1,2,3,4) ; SELECT DISTINCT fn.dept_iddept_id,fcoam.dp_acc_idacc_id,fn.cat,fn.sub_cat,fn.amount FROMFET_ABM_FA_NBV fn, FET_ABM_FA_DP_RATE_MAP fdr, FET_ABM_FA_COC_ACC_MAP fcoam WHERE fn.cat= fdr.cat ANDfn.sub_cat = fdr.sub_cat ANDfn.cat= fcoam.cat ANDfn.sub_cat || '-NON NETWORK'= fcoam.sub_cat AND fdr.cat_noNOT IN (1,2,3,4) ; Table name alias UpperCase & Left Alignment

76 Exercise 4 由於 Chen (Last Name) 表現優異, 董事長決定 親自表揚, 請找出他的工作地點 (City) 在銷售 (Sales) 部門, 每月員工薪資支出是多少 ( 請列出部門名稱及薪資支出 ) 請用計算薪資大於全公司平均薪資的員工數 請列出平均薪資大於全公司平均薪資的部門 ( 列 出部門名稱)

77 DAY 2

78 ERD

79 Data Models Model of system in client’s mind Entity model Table model of entity model Database Server Table on disk

80 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

81 Table Instance Chart Column NameData TypeKey TypeFk TableNull department_idNumber(4)PK1N department_nameVarchar2(30)N manager_idNumber(6)FK1employees.emp_id Y location_idNumber(4)FK2location.loc ation_id Y DEPARTMENTS Table

82 Creating Tables

83 Database objects ObjectDescription TableBasic unit of storage composed of rows and columns ViewLogically represents subsets of data from one or more tables SequenceGenerate primary key values IndexImproves the performance of some queries SynonymAlternate name for an object Program UnitProcedure, function or package of SQL and PL/SQL statement

84 Datatypes DatatypeDescription VARCHAR2(size)Variable length character value,max 4000 bytes CHAR(size)Fixed length character value, max 2000 bytes NUMBER(precision,scale) Number Values DATEDate & Time values, January 1, 4712 BC to December 31, 9999 AD. CLOBCharacter large object, max 4Gb BLOBBinary large object, max 4Gb

85 Number Type

86 Data Integrity Constraints ConstraintDescription NOT NULLSpecifies that this may not contain a null value UNIQUESpecifies a column or combination of columns whose values must be unique for all rows in the table. PRIMARY KEYUniquely identifies each row of the table. FOREIGN KEYEstablishes and enforces a foreign key relationship between the column and a column of the referenced table. CHECKSpecifies a condition that must be true.

87 Creating Table (example)

88

89 Create Table (example)

90 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

91 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

92 Checking Constraint on a Table SELECT CONSTRAINT_NAME,COLUMN_NAME,POSITION FROM USER_CONS_COLUMNS WHERE TABLE_NAME =‘DEPARTMENTS' ORDER BY CONSTRAINT_NAME,POSITION SELECT CONSTRAINT_NAME,COLUMN_NAME,POSITION FROM USER_CONS_COLUMNS WHERE TABLE_NAME =‘DEPARTMENTS' ORDER BY CONSTRAINT_NAME,POSITION

93 Manipulating Data

94 DML & Transaction Control CommandDescription INSERTAdd new rows to the table UPDATEModify existing rows in the table DELETERemove existing rows in the table COMMITMake all pending changes permanent SAVEPOINTAllows a rollback to that savepoint maker ROLLBACKDiscards all pending data changes

95 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

96 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_id FROM employees WHERE 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_id FROM employees WHERE job_id=‘SH_CLERK’

97 Update Rows in a Tables UPDATE employees SET salary = salary * 1.05 WHERE job_id ='SA_REP' UPDATE employees SET salary = salary * 1.05 WHERE job_id ='SA_REP' Example UPDATE table SET column = value, [column = value ] [ WHERE condition ] ; UPDATE table SET column = value, [column = value ] [ WHERE condition ] ; Syntax

98 Deleting Rows from a Table DELETE employees WHERE job_id like ‘IT%’ DELETE employees WHERE job_id like ‘IT%’ Example DELETE table [ WHERE condition ] ; DELETE table [ WHERE condition ] ; Syntax

99 Data Consistency (Transaction) Atomicity ( 不可分割性 ) Durability ( 持續性 )

100 COMMIT and ROLLBACK Ensure data consistency Preview data changes before making changes permanent Group logically related operations

101 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

102 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

103 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.

104 State of the Data After ROLLBACK Data change are undone Previous state of the data restored Locks on the affected rows are released

105 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

106 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

107 Creating Sequences CREATE SEQUENCE S1 INCREMENT BY 2 START WITH 5 MINVALUE 1 MAXVALUE 10 NOCACHE CYCLE CREATE SEQUENCE S1 INCREMENT BY 2 START WITH 5 MINVALUE 1 MAXVALUE 10 NOCACHE CYCLE Example 5  8  1  4  7  10  1  4  7  10

108 What Is a View ?

109 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.

110 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

111 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) AS SELECT employee_id,last_name,job_id,manager_id,department_id FROM employees WHERE department_id= 60 CREATE VIEW STAFF_60_V (employee_id,last_name,job_id,manager_id,department_id) AS SELECT employee_id,last_name,job_id,manager_id,department_id FROM employees WHERE department_id= 60

112 Creating a Complex View (example) Creating a complex view that contain group function to display values from two tables CREATE VIEW DEPT_SALARY_VIEW AS SELECT d.department_name,SUM(salary) sum_salary,MIN(SALARY) min_salary,MAX(SALARY) max_salary FROM EMPLOYEES e,DEPARTMENTS d WHERE e.department_id = d.department_id GROUP BY d.department_name CREATE VIEW DEPT_SALARY_VIEW AS SELECT d.department_name,SUM(salary) sum_salary,MIN(SALARY) min_salary,MAX(SALARY) max_salary FROM EMPLOYEES e,DEPARTMENTS d WHERE e.department_id = d.department_id GROUP BY d.department_name

113 Exercise 5 Create View 列出員工姓名及主管姓名 (last name & first name) 由於業務部門績效良好, 董事長決定全部加薪 10%, 請 更改他們的薪資, 並列出薪資超出該職務( job_id) 上限 的人員 公司決定自即日起將 IT 工作外包, 請將 IT 人員自 employees Table 中移除,並將相關資料放至 job_history

114 What Is a Index ? Database Object Each index is composed of column values and pointers (or ROWID) Indexes is maintained and used by RDBMS

115 Index Type By constraint – Unique – Non-unique By constitution – Single Column – Concatenated or Composite

116 How are Indexes Created ? Automatically – A unique index are created when you define PRIMARY KEY or UNIQUE KEY constraint in a table defination Manually – CREATE INDEX command

117 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

118 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

119 Confirming Indexes USER_INDEXES USER_IND_COLUMNS

120 DAY 3

121 PL/SQL

122 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)

123 Example PL/SQL Block DECLARE Emp_name VARCHAR2(10); Emp_number INTEGER; Empno_out_of_range EXCEPTION; BEGIN Emp_number := 10001; IF Emp_number > 9999 OR Emp_number < 1000 THEN RAISE Empno_out_of_range; ELSE SELECT Ename INTO Emp_name FROM Emp_tab WHERE Empno = Emp_number; DBMS_OUTPUT.PUT_LINE('Employee name is' || Emp_name); END IF; EXCEPTION WHEN Empno_out_of_range THEN DBMS_OUTPUT.PUT_LINE('Employee number' || Emp_number ||'is out of range.'); END;

124 Block Types Anonymous Procedure [DECLARE] BEGIN -- Statement [EXCEPTION] END; [DECLARE] BEGIN -- Statement [EXCEPTION] END; PROCEDURE name IS BEGIN -- Statement [EXCEPTION] END; PROCEDURE name IS BEGIN -- Statement [EXCEPTION] END; Function FUNCTION name RETURN datatype IS BEGIN -- Statement RETURN value; [EXCEPTION] END; FUNCTION name RETURN datatype IS BEGIN -- Statement RETURN value; [EXCEPTION] END;

125 Program Constructs Stored Procedure and Function (Package) Application Procedure and Function (Package) Database Trigger Application Trigger (Form,Report) Anonymous Block

126 Declare Variables PL/SQL variables – Scalar – Composite – Reference (Pointer) – LOB (Large Objects)

127 Built-in Datatypes Quick Ref.

128 Declaring PL/SQL Variable identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr ]; Declare v_adjust_amountNUMBERNOT NULL:=0; v_nbv_amountNUMBER:=0; v_dis_nbv_amountNUMBER:=0; Declare v_adjust_amountNUMBERNOT NULL:=0; v_nbv_amountNUMBER:=0; v_dis_nbv_amountNUMBER:=0; Syntax Example

129 Declaring Variables with the %TYPE Attribute Example … DECLARE v_ename emp.ename%TYPE; v_balance NUMBER(7,2); … DECLARE v_ename emp.ename%TYPE; v_balance NUMBER(7,2); …

130 Base Scalar Datatypes VARCHAR2(maximun_length) NUMBER[(precision,scale)] DATE CHAR(maximun_length) ………

131 Code Naming Convention IdentifierNaming ConversionExample Variablev_namev_sal Constantc_namec_company_name Cursorname_cursoremp_cursor Exceptione_namee_too_many Table typename_table_typeamount_table_type Tablename_tableorder_total_table Record Typename_record_typeemp_record_type Recordname_recordcustomer_record

132 SELECT statement in PL/SQL SELECT select_list INTO{ variable_name [,variable_name].... | record_name } FROMtable WHEREcondition; SELECT select_list INTO{ variable_name [,variable_name].... | record_name } FROMtable WHEREcondition; Retrieve data from the database with SELECT Syntax

133 SELECT statement in PL/SQL INTO clause Queries Must Return One and Only One Row – NO_DATA_FOUND – TOO_MANY_ROWS

134 Simple PL/SQL Block DECLARE v_deptnoNUMBER(2); v_locVARCHAR2(15); BEGIN SELECTdeptno,loc INTOv_deptno,v_loc FROMdept WHEREdname='SALES'; DBMS_OUTPUT.PUT_LINE(TO_CHAR(v_deptno)); DBMS_OUTPUT.PUT_LINE(v_loc); END; DECLARE v_deptnoNUMBER(2); v_locVARCHAR2(15); BEGIN SELECTdeptno,loc INTOv_deptno,v_loc FROMdept WHEREdname='SALES'; DBMS_OUTPUT.PUT_LINE(TO_CHAR(v_deptno)); DBMS_OUTPUT.PUT_LINE(v_loc); END;

135 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

136 Determining Variable Scope DECLARE v_salNUMBER(7,2) := 6000; v_commNUMBER(7,2) := v_sal * 0.2; v_messageVARCHAR2(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_salNUMBER(7,2) := 6000; v_commNUMBER(7,2) := v_sal * 0.2; v_messageVARCHAR2(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;

137 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

138 Writing Control Structures IF statement LOOP GOTO

139 IF Statement Conditional IF statements – IF-THEN-END IF – IF-THEN-ELSE-END IF – IF-THEN-ELSIF-END IF

140 Simple IF Statement... IF v_ename = 'MILLER' THEN THEN 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' THEN THEN 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;

141 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;

142 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

143 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

144 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; > 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; > v_dummy := 1; END;

145 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

146 Composite Datatypes PL/SQL RECORDS PL/SQL TABLES

147 PL/SQL Record DECLARE TYPE emp_record_type IS RECORD (ename VARCHAR2(10), job VARCHAR2(9), sal NUMBER(7,2)); emp_record emp_record_type; BEGIN END; DECLARE TYPE emp_record_type IS RECORD (ename VARCHAR2(10), job VARCHAR2(9), sal NUMBER(7,2)); emp_record emp_record_type; BEGIN END;

148 The %ROWTYPE Attribute DECLARE emp_record emp%ROWTYPE; BEGIN …. END; DECLARE emp_record emp%ROWTYPE; BEGIN …. END;

149 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;

150 Writing Explicit Cursor

151 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

152 Explicit Cursor Function 7369 SMITH CLERK 7499 ALLEN SALESMAN 7521 WARD SALESMAN 7566 JONES MANAGER 7654 MARTIN SALESMAN 7698 BLAKE MANAGER cursor Current row

153 Controlling Explicit Cursor DECLARE FETCHCLOSE OPEN EMPTY? NO YES

154 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;

155 Explicit Cursor Attribute AttributeTypeDescription %ISOPENBooleanEvaluates to TRUE if the cursor is open %NOTFOUNDBooleanEvaluates to TRUE if the most recent fetch does not return a row %FOUNDBooleanEvaluates to TRUE if the most recent fetch returns a row %ROWCOUNTNumberEvaluates to the total number of rows returned so far

156 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 occurs END; 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 occurs END;

157 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

158 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

159 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

160 The FOR UPDATE Clause Lock the affected rows when the cursor is opened You should not commit across fetched from a explicit cursor 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

161 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;

162 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 emp SET sal = sal * 1.10 WHERE 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 emp SET sal = sal * 1.10 WHERE CURRENT OF sal_cursor; END LOOP; END;

163 Summary (Cursor) Cursor type: – Implicit cursors:Used for all DML statements and single-row queries – 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

164 Handling Exceptions

165 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

166 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

167 Exception Types Predefined Oracle Server Non-predefined Oracle Server User-defined Implicitly raised Explicitly raised

168 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

169 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;

170 Predefined Oracle Server Errors

171 Using SQLCODE & SQLERRM

172 User-Defined Exception

173 How Exception Propagate

174

175

176 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 -800 More than one employee with a salary of 3000 No employee with a salary 6000

177 Stored Procedures & Functions

178 Create Stored Procedure (example) CREATE OR REPLACE PROCEDURE raise_salary (emp_id INTEGER, amount NUMBER) IS current_salary NUMBER; salary_missing EXCEPTION; BEGIN SELECT sal INTO current_salary FROM emp WHERE empno = emp_id; IF current_salary IS NULL THEN RAISE salary_missing; ELSE UPDATE emp SET sal = sal + amount WHERE empno = emp_id; END IF; EXCEPTION WHEN NO_DATA_FOUND THEN INSERT INTO emp_audit VALUES (emp_id, 'No such number'); WHEN salary_missing THEN INSERT INTO emp_audit VALUES (emp_id, 'Salary is null'); END raise_salary; CREATE OR REPLACE PROCEDURE raise_salary (emp_id INTEGER, amount NUMBER) IS current_salary NUMBER; salary_missing EXCEPTION; BEGIN SELECT sal INTO current_salary FROM emp WHERE empno = emp_id; IF current_salary IS NULL THEN RAISE salary_missing; ELSE UPDATE emp SET sal = sal + amount WHERE empno = emp_id; END IF; EXCEPTION WHEN NO_DATA_FOUND THEN INSERT INTO emp_audit VALUES (emp_id, 'No such number'); WHEN salary_missing THEN INSERT INTO emp_audit VALUES (emp_id, 'Salary is null'); END raise_salary;

179 Execute Stored Procedure 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;

180 Create Stored Function (example) CREATE OR REPLACE FUNCTION emp_sal_query (i_empno NUMBER) RETURN NUMBER IS v_sal NUMBER; BEGIN SELECT sal INTO v_sal FROM emp WHERE empno = i_empno; RETURN v_sal; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN NULL; END emp_sal_query; CREATE OR REPLACE FUNCTION emp_sal_query (i_empno NUMBER) RETURN NUMBER IS v_sal NUMBER; BEGIN SELECT sal INTO v_sal FROM emp WHERE empno = i_empno; RETURN v_sal; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN NULL; END emp_sal_query;

181 Execute Stored Function SELECT emp_sal_query(7369) FROM dual; 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;

182 Practice 9

183 SQL*Loader Overview

184 Discarded and Rejected Records

185 SQL*Loader Case Studies $ORACLE_HOME/rdbms/demo/ulcase*.*

186 Recommendable Oracle Essentials:Oracle 9i,Oracle8i & Oracle8– O’RELLY Oracle Design – O’REILLY Oracle SQL High-Performance Tuning—Prentice Hall Oracle 資料庫管理實務 — 旗標 Oracle 9i Java 程式設計 – 金禾


Download ppt "Oracle SQL introduction. 使用聲明 請尊重智慧財產權 本資料僅限高雄應用科技大學資管系教學使用 未經允許請勿擅自複製、散佈、使用."

Similar presentations


Ads by Google