Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL: Part 4 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial.

Similar presentations


Presentation on theme: "SQL: Part 4 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial."— Presentation transcript:

1 SQL: Part 4 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial use. Do not redistribute. Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial use. Do not redistribute.

2 2 OUTLINE  Views  Cursors  Triggers  Views  Cursors  Triggers

3 Views

4 4 Database Objects Description Basic unit of storage; composed of rows and columns Logically represents subsets of data from one or more tables Generates primary key values Improves the performance of some queries Alternative name for an object Object Table View Sequence Index Synonym

5 5 What Is a View? EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ----- ------- --------- ----- --------- ----- ----- ------- 7839 KING PRESIDENT 17-NOV-81 5000 10 7698 BLAKE MANAGER 7839 01-MAY-81 2850 30 7782 CLARK MANAGER 7839 09-JUN-81 2450 10 7566 JONES MANAGER 7839 02-APR-81 2975 20 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30 7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30 7900 JAMES CLERK 7698 03-DEC-81 950 30 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 7902 FORD ANALYST 7566 03-DEC-81 3000 20 7369 SMITH CLERK 7902 17-DEC-80 800 20 7788 SCOTT ANALYST 7566 09-DEC-82 3000 20 7876 ADAMS CLERK 7788 12-JAN-83 1100 20 7934 MILLER CLERK 7782 23-JAN-82 1300 10 EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ----- ------- --------- ----- --------- ----- ----- ------- 7839 KING PRESIDENT 17-NOV-81 5000 10 7698 BLAKE MANAGER 7839 01-MAY-81 2850 30 7782 CLARK MANAGER 7839 09-JUN-81 2450 10 7566 JONES MANAGER 7839 02-APR-81 2975 20 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30 7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30 7900 JAMES CLERK 7698 03-DEC-81 950 30 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 7902 FORD ANALYST 7566 03-DEC-81 3000 20 7369 SMITH CLERK 7902 17-DEC-80 800 20 7788 SCOTT ANALYST 7566 09-DEC-82 3000 20 7876 ADAMS CLERK 7788 12-JAN-83 1100 20 7934 MILLER CLERK 7782 23-JAN-82 1300 10 EMP Table EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ----- -------- --------- ---- --------- ------ ----- ------ - 7839 KING PRESIDENT 17-NOV-81 5000 10 7782 CLARK MANAGER 7839 09-JUN-81 1500 300 10 7934 MILLER CLERK 7782 23-JAN-82 1300 10 7566 JONES MANAGER 7839 02-APR-81 2975 20 7788 SCOTT ANALYST 7566 09-DEC-82 3000 20 7876 ADAMS CLERK 7788 12-JAN-83 1100 20 7369 SMITH CLERK 7902 17-DEC-80 800 20 7902 FORD ANALYST 7566 03-DEC-81 3000 20 7698 BLAKE MANAGER 7839 01-MAY-81 2850 30 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30 7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30 7900 JAMES CLERK 7698 03-DEC-81 950 30 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ----- -------- --------- ---- --------- ------ ----- ------ - 7839 KING PRESIDENT 17-NOV-81 5000 10 7782 CLARK MANAGER 7839 09-JUN-81 1500 300 10 7934 MILLER CLERK 7782 23-JAN-82 1300 10 7566 JONES MANAGER 7839 02-APR-81 2975 20 7788 SCOTT ANALYST 7566 09-DEC-82 3000 20 7876 ADAMS CLERK 7788 12-JAN-83 1100 20 7369 SMITH CLERK 7902 17-DEC-80 800 20 7902 FORD ANALYST 7566 03-DEC-81 3000 20 7698 BLAKE MANAGER 7839 01-MAY-81 2850 30 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30 7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30 7900 JAMES CLERK 7698 03-DEC-81 950 30 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 EMPNO ENAME JOB ------ -------- ----------- 7839 KING PRESIDENT 7782 CLARK MANAGER 7934 MILLER CLERK EMPVU10 View EMPVU10 View

6 6 Why Use Views? To restrict database access To make complex queries easy To allow data independence To present different views of the same data To restrict database access To make complex queries easy To allow data independence To present different views of the same data

7 7 Simple vs. Complex Views FeatureSimple ViewsComplex Views Number of tablesOneOne or more Contain functionsNoYes Contain groups of dataNoYes DML through viewYesNot always FeatureSimple ViewsComplex Views Number of tablesOneOne or more Contain functionsNoYes Contain groups of dataNoYes DML through viewYesNot always

8 8 Creating a View You embed a subquery within the CREATE VIEW statement. The subquery can contain complex SELECT syntax. The subquery cannot contain an ORDER BY clause. You embed a subquery within the CREATE VIEW statement. The subquery can contain complex SELECT syntax. The subquery cannot contain an ORDER BY clause. CREATE [OR ALTER] VIEW view [(alias[, alias]...)] [WITH ENCRYPTION] AS subquery [WITH CHECK OPTION] CREATE [OR ALTER] VIEW view [(alias[, alias]...)] [WITH ENCRYPTION] AS subquery [WITH CHECK OPTION]

9 9 Creating a View Create a view, EMPVU10, that contains details of employees in department 10. SQL> CREATE VIEW empvu10 2 AS SELECTempno, ename, job 3 FROMemp 4 WHEREdeptno = 10 View created.

10 10 Creating a View Create a view by using column aliases in the sub-query. Select the columns from this view by the given alias names. Create a view by using column aliases in the sub-query. Select the columns from this view by the given alias names. SQL> CREATE VIEW salvu30 2 AS SELECTempno EMPLOYEE_NUMBER, ename NAME, 3sal SALARY 4 FROMemp 5 WHEREdeptno = 30 View created.

11 11 Retrieving Data from a View EMPLOYEE_NUMBER NAME SALARY --------------- ---------- --------- 7698 BLAKE 2850 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 7521 WARD 1250 6 rows selected. EMPLOYEE_NUMBER NAME SALARY --------------- ---------- --------- 7698 BLAKE 2850 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 7521 WARD 1250 6 rows selected. SQL> SELECT * 2 FROMsalvu30

12 12 Creating a Complex View Create a complex view that contains group functions to display values from two tables. SQL> CREATE VIEWdept_sum_vu 2 (name, minsal, maxsal, avgsal) 3 AS SELECTd.dname, MIN(e.sal), MAX(e.sal), 4AVG(e.sal) 5 FROMemp e, dept d 6 WHEREe.deptno = d.deptno 7 GROUP BY d.dname View created.

13 13 Rules for Performing DML Operations on a View You can perform DML operations on simple views. You cannot remove a row if the view contains the following: – Group functions – A GROUP BY clause – The DISTINCT keyword You can perform DML operations on simple views. You cannot remove a row if the view contains the following: – Group functions – A GROUP BY clause – The DISTINCT keyword

14 14 Rules for Performing DML Operations on a View You cannot modify data in a view if it contains: – Any of the conditions mentioned in the previous slide – Columns defined by expressions – The ROWNUM pseudocolumn You cannot add data if: – The view contains any of the conditions mentioned above or in the previous slide – There are NOT NULL columns in the base tables that are not selected by the view You cannot modify data in a view if it contains: – Any of the conditions mentioned in the previous slide – Columns defined by expressions – The ROWNUM pseudocolumn You cannot add data if: – The view contains any of the conditions mentioned above or in the previous slide – There are NOT NULL columns in the base tables that are not selected by the view

15 15 Removing a View Remove a view without losing data because a view is based on underlying tables in the database. SQL> DROP VIEW empvu10 View dropped. DROP VIEW view

16 16 Summary A view is derived from data in other tables or other views. A view provides the following advantages: – Restricts database access – Simplifies queries – Provides data independence – Allows multiple views of the same data – Can be dropped without removing the underlying data A view is derived from data in other tables or other views. A view provides the following advantages: – Restricts database access – Simplifies queries – Provides data independence – Allows multiple views of the same data – Can be dropped without removing the underlying data

17 Cursors

18 18 Using Cursors Cursors provide a “handle” on query results for further processing; you need to Cursors provide a “handle” on query results for further processing; you need to – DECLARE the cursor with the SELECT statement –OPEN the cursor –FETCH rows from the cursor –USE the rows –CLOSE the cursor –DEALLOCATE the cursor Cursors provide a “handle” on query results for further processing; you need to Cursors provide a “handle” on query results for further processing; you need to – DECLARE the cursor with the SELECT statement –OPEN the cursor –FETCH rows from the cursor –USE the rows –CLOSE the cursor –DEALLOCATE the cursor

19 19 General Syntax for Cursors DECLARE cursorname CURSOR DECLARE cursorname CURSOR FOR SELECT column FROM table [condition] OPEN cursorname FETCH NEXT FROM cursorname INTO variable USE (The values in the variable can now be used) CLOSE cursorname DEALLOCATE cursorname DECLARE cursorname CURSOR DECLARE cursorname CURSOR FOR SELECT column FROM table [condition] OPEN cursorname FETCH NEXT FROM cursorname INTO variable USE (The values in the variable can now be used) CLOSE cursorname DEALLOCATE cursorname

20 20 Example 1 declare top_emp cursor for select FirstName+" "+LastName from Employees inner join Orders on Orders.EmployeeID=Employees.EmployeeID group by FirstName, LastName having count(OrderID)>100 open top_emp declare @e_name char(20) fetch next from top_emp into @e_name declare top_emp cursor for select FirstName+" "+LastName from Employees inner join Orders on Orders.EmployeeID=Employees.EmployeeID group by FirstName, LastName having count(OrderID)>100 open top_emp declare @e_name char(20) fetch next from top_emp into @e_name

21 21 Example (contd.) print "Employees with Sales > 100" print "--------------------------" while (@@fetch_status=0) begin print @e_name fetch next from top_emp into @e_name end close top_emp deallocate top_emp print "Employees with Sales > 100" print "--------------------------" while (@@fetch_status=0) begin print @e_name fetch next from top_emp into @e_name end close top_emp deallocate top_emp

22 22 Results Equivalent To select FirstName+" "+LastName [Employees with Sales > 100] from Employees inner join Orders on Orders.EmployeeID=Employees.EmployeeID group by FirstName, LastName having count(OrderID)>100 select FirstName+" "+LastName [Employees with Sales > 100] from Employees inner join Orders on Orders.EmployeeID=Employees.EmployeeID group by FirstName, LastName having count(OrderID)>100

23 Triggers

24 24 Triggers Defines an action to be taken when a specified event occurs Defines an action to be taken when a specified event occurs Events Events –INSERT –UPDATE –DELETE Defines an action to be taken when a specified event occurs Defines an action to be taken when a specified event occurs Events Events –INSERT –UPDATE –DELETE

25 25 Triggers: How They Work When an INSERT trigger occurs, a temporary INSERTED table is created When an INSERT trigger occurs, a temporary INSERTED table is created When a DELETE trigger occurs, a temporary DELETED table is created When a DELETE trigger occurs, a temporary DELETED table is created These tables may be accessed by the trigger UPDATE triggers work via UPDATE triggers work via IF UPDATE(column) When an INSERT trigger occurs, a temporary INSERTED table is created When an INSERT trigger occurs, a temporary INSERTED table is created When a DELETE trigger occurs, a temporary DELETED table is created When a DELETE trigger occurs, a temporary DELETED table is created These tables may be accessed by the trigger UPDATE triggers work via UPDATE triggers work via IF UPDATE(column)

26 26 Triggers: Limits on Syntax Cannot contain the following statements CREATE, ALTER, DROP GRANT, REVOKE, DENY LOAD and RESTORE RECONFIGURE TRUNCATE TABLE UPDATE STATISTICS SELECT INTO (because it creates a table) Cannot contain the following statements CREATE, ALTER, DROP GRANT, REVOKE, DENY LOAD and RESTORE RECONFIGURE TRUNCATE TABLE UPDATE STATISTICS SELECT INTO (because it creates a table)

27 27 Triggers: Syntax CREATE TRIGGER triggername ON table [WITH ENCRYPTION] FOR [DELETE|INSERT|UPDATE] [WITH APPEND] [NOT FOR REPLICATION] AS sqlstatement[, …n] CREATE TRIGGER triggername ON table [WITH ENCRYPTION] FOR [DELETE|INSERT|UPDATE] [WITH APPEND] [NOT FOR REPLICATION] AS sqlstatement[, …n]

28 28 Triggers: An Example (This trigger prompts the order clerk to award first time customers a 10% discount.) create trigger InsertCustomerOrders on Orders for insert ‑‑ Triggering event as declare @CustName char(30) set @CustName=(select CompanyName from Customers inner join Inserted on Customers.CustomerID=Inserted.CustomerID) if (select count(p.CustomerID) from Orders p inner join inserted i on p.CustomerID=i.CustomerID)=1 begin print 'This is first order placed by '+@CustName+'. ' print 'This is first order placed by '+@CustName+'. ' print 'Please give this customer a 10% discount on all purchases made today.' print 'Please give this customer a 10% discount on all purchases made today.'end (This trigger prompts the order clerk to award first time customers a 10% discount.) create trigger InsertCustomerOrders on Orders for insert ‑‑ Triggering event as declare @CustName char(30) set @CustName=(select CompanyName from Customers inner join Inserted on Customers.CustomerID=Inserted.CustomerID) if (select count(p.CustomerID) from Orders p inner join inserted i on p.CustomerID=i.CustomerID)=1 begin print 'This is first order placed by '+@CustName+'. ' print 'This is first order placed by '+@CustName+'. ' print 'Please give this customer a 10% discount on all purchases made today.' print 'Please give this customer a 10% discount on all purchases made today.'end

29 29 Invoking the Insert Trigger Doing the following: insert into Orders (CustomerID, EmployeeID, OrderDate) values (‘OU', 4, 2000-7-24) Will result in: This is first order placed by University. Please give this customer a 10% discount on all purchases made today. Doing the following: insert into Orders (CustomerID, EmployeeID, OrderDate) values (‘OU', 4, 2000-7-24) Will result in: This is first order placed by University. Please give this customer a 10% discount on all purchases made today.

30 30 A Delete Trigger (This trigger automatically increments the inventory in the Products table when an order is cancelled.) create trigger DeleteOrders on [Order Details] for delete as declare @units smallint, @prod char(2), @sunits smallint, @funits smallint set @sunits=(select p.UnitsInStock from Products p inner join Deleted d on p.ProductID=d.ProductID) set @units=(select d.Quantity from Deleted d) set @funits=@sunits+@units set @prod=(select ProductID from deleted) (This trigger automatically increments the inventory in the Products table when an order is cancelled.) create trigger DeleteOrders on [Order Details] for delete as declare @units smallint, @prod char(2), @sunits smallint, @funits smallint set @sunits=(select p.UnitsInStock from Products p inner join Deleted d on p.ProductID=d.ProductID) set @units=(select d.Quantity from Deleted d) set @funits=@sunits+@units set @prod=(select ProductID from deleted)

31 31 Delete Trigger (contd.) begin update Products set UnitsInStock=@funits where ProductID=@prod print 'Updating inventory for '+convert(char(2),@prod) print 'Initial units in stock '+convert(char(2),@sunits) print 'Restoring '+convert(char(2),@units)+' from cancelled order' print 'Current units in stock '+convert(char(2),@funits) endbegin update Products set UnitsInStock=@funits where ProductID=@prod print 'Updating inventory for '+convert(char(2),@prod) print 'Initial units in stock '+convert(char(2),@sunits) print 'Restoring '+convert(char(2),@units)+' from cancelled order' print 'Current units in stock '+convert(char(2),@funits) end

32 32 Invoking the Delete Trigger Doing the following: delete from [Order Details] where OrderID=11084 Will result in: Updating inventory for 11 Initial units in stock 65 Restoring 15 from cancelled order Current units in stock 80 Doing the following: delete from [Order Details] where OrderID=11084 Will result in: Updating inventory for 11 Initial units in stock 65 Restoring 15 from cancelled order Current units in stock 80

33 33 Another Insert Trigger This trigger implements a new business rule requiring all order quantities to exceed 5 units. create trigger InsertOrderDetail on [Order Details] for insert as if (select Quantity from Inserted)<5 begin print 'This is a wholesale business.' print 'All order quantities must be at least 5 units. ' rollback transaction end This trigger implements a new business rule requiring all order quantities to exceed 5 units. create trigger InsertOrderDetail on [Order Details] for insert as if (select Quantity from Inserted)<5 begin print 'This is a wholesale business.' print 'All order quantities must be at least 5 units. ' rollback transaction end

34 34 Invoking the Trigger Doing the following: insert into [order details] values (11084, 11, 14, 2, 0) Will result in: The following being displayed: This is a wholesale business. All order quantities must be at least 5 units. Order Details table – No record added Doing the following: insert into [order details] values (11084, 11, 14, 2, 0) Will result in: The following being displayed: This is a wholesale business. All order quantities must be at least 5 units. Order Details table – No record added

35 35 Viewing Information on Triggers Listing of trigger code SP_HELPTEXT triggername Listing objects referenced by trigger SP_DEPENDS triggername Listing triggers on a table SP_HELPTRIGGER tablename Listing of trigger code SP_HELPTEXT triggername Listing objects referenced by trigger SP_DEPENDS triggername Listing triggers on a table SP_HELPTRIGGER tablename


Download ppt "SQL: Part 4 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial."

Similar presentations


Ads by Google