Date post: | 17-Dec-2015 |
Category: |
Documents |
Upload: | lenard-atkinson |
View: | 215 times |
Download: | 1 times |
SQL: Part 4SQL: 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
OUTLINEOUTLINE
ViewsViews
CursorsCursors
TriggersTriggers
ViewsViews
CursorsCursors
TriggersTriggers
4
Database ObjectsDatabase 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
What Is a View?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 TableEMP TableEMPNO 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 ViewEMPVU10 View
6
Why Use Views?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
Simple vs. Complex Views Simple vs. Complex Views
Feature Simple Views Complex Views
Number of tables One One or more
Contain functions No Yes
Contain groups of data No Yes
DML through view Yes Not always
8
Creating a ViewCreating 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
Creating a ViewCreating a View
• Create a view, EMPVU10, that contains details of employees in department 10.
• Create a view, EMPVU10, that contains details of employees in department 10.
SQL> CREATE VIEW empvu10 2 AS SELECT empno, ename, job 3 FROM emp 4 WHERE deptno = 10View created.View created.
10
Creating a ViewCreating 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 SELECT empno EMPLOYEE_NUMBER, ename NAME, 3 sal SALARY 4 FROM emp 5 WHERE deptno = 30View created.View created.
11
Retrieving Data from a ViewRetrieving 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 FROM salvu30
12
Creating a Complex ViewCreating a Complex View
Create a complex view that contains group Create a complex view that contains group functions to display values from two tables.functions to display values from two tables.Create a complex view that contains group Create a complex view that contains group functions to display values from two tables.functions to display values from two tables.
SQL> CREATE VIEW dept_sum_vu 2 (name, minsal, maxsal, avgsal) 3 AS SELECT d.dname, MIN(e.sal), MAX(e.sal), 4 AVG(e.sal) 5 FROM emp e, dept d 6 WHERE e.deptno = d.deptno 7 GROUP BY d.dnameView created.View created.
13
Rules for Performing DML Operations on a View
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
Rules for Performing DML Operations on a View
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
Removing a ViewRemoving a View
Remove a view without losing data Remove a view without losing data because a view is based on underlying because a view is based on underlying tables in the database.tables in the database.
Remove a view without losing data Remove a view without losing data because a view is based on underlying because a view is based on underlying tables in the database.tables in the database.
SQL> DROP VIEW empvu10 View dropped.View dropped.
DROP VIEW view DROP VIEW view
16
SummarySummary
• 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
18
Using CursorsUsing Cursors
• Cursors provide a “handle” on query Cursors provide a “handle” on query results for further processing; you need toresults 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 Cursors provide a “handle” on query results for further processing; you need toresults 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
General Syntax for CursorsGeneral Syntax for Cursors
DECLARE cursorname CURSORDECLARE cursorname CURSOR
FOR
SELECT column FROM table [condition]
OPEN cursornameOPEN cursorname
FETCH NEXT FROM cursorname INTO variableFETCH NEXT FROM cursorname INTO variable
USE USE (The values in the variable can now be used)(The values in the variable can now be used)
CLOSE cursorname
DEALLOCATE cursorname
DECLARE cursorname CURSORDECLARE cursorname CURSOR
FOR
SELECT column FROM table [condition]
OPEN cursornameOPEN cursorname
FETCH NEXT FROM cursorname INTO variableFETCH NEXT FROM cursorname INTO variable
USE USE (The values in the variable can now be used)(The values in the variable can now be used)
CLOSE cursorname
DEALLOCATE cursorname
20
Example 1Example 1
declare top_emp cursordeclare 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 cursordeclare 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
Example (contd.)Example (contd.)
print "Employees with Sales > 100"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 "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
Results Equivalent ToResults 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
24
TriggersTriggers
• Defines an action to be taken when a Defines an action to be taken when a specified event occursspecified event occurs
• EventsEvents
– INSERT
– UPDATE
– DELETE
• Defines an action to be taken when a Defines an action to be taken when a specified event occursspecified event occurs
• EventsEvents
– INSERT
– UPDATE
– DELETE
25
Triggers: How They WorkTriggers: How They Work
• When an INSERT trigger occurs, a When an INSERT trigger occurs, a temporary temporary INSERTEDINSERTED table is created table is created
• When a DELETE trigger occurs, a When a DELETE trigger occurs, a temporary temporary DELETEDDELETED table is created table is created
These tables may be accessed by the triggerThese tables may be accessed by the trigger
• UPDATE triggers work via UPDATE triggers work via
IF UPDATE(column)
• When an INSERT trigger occurs, a When an INSERT trigger occurs, a temporary temporary INSERTEDINSERTED table is created table is created
• When a DELETE trigger occurs, a When a DELETE trigger occurs, a temporary temporary DELETEDDELETED table is created table is created
These tables may be accessed by the triggerThese tables may be accessed by the trigger
• UPDATE triggers work via UPDATE triggers work via
IF UPDATE(column)
26
Triggers: Limits on SyntaxTriggers: Limits on Syntax
Cannot contain the following statementsCannot 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 statementsCannot 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
Triggers: SyntaxTriggers: 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
Triggers: An ExampleTriggers: An Example
(This trigger prompts the order clerk to award first time customers a 10% discount.)(This trigger prompts the order clerk to award first time customers a 10% discount.)
create trigger InsertCustomerOrderscreate trigger InsertCustomerOrders
on Orderson Orders
for insert for insert ‑‑ Triggering event‑‑ Triggering event
asas
declare @CustName char(30)declare @CustName char(30)
set @CustName=(select CompanyName from Customers inner join set @CustName=(select CompanyName from Customers inner join Inserted on Customers.CustomerID=Inserted.CustomerID)Inserted on Customers.CustomerID=Inserted.CustomerID)
if (select count(p.CustomerID) from Orders p inner join if (select count(p.CustomerID) from Orders p inner join inserted i on p.CustomerID=i.CustomerID)=1inserted i on p.CustomerID=i.CustomerID)=1
beginbegin
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 print 'Please give this customer a 10% discount on all purchases made today.'all purchases made today.'
endend
(This trigger prompts the order clerk to award first time customers a 10% discount.)(This trigger prompts the order clerk to award first time customers a 10% discount.)
create trigger InsertCustomerOrderscreate trigger InsertCustomerOrders
on Orderson Orders
for insert for insert ‑‑ Triggering event‑‑ Triggering event
asas
declare @CustName char(30)declare @CustName char(30)
set @CustName=(select CompanyName from Customers inner join set @CustName=(select CompanyName from Customers inner join Inserted on Customers.CustomerID=Inserted.CustomerID)Inserted on Customers.CustomerID=Inserted.CustomerID)
if (select count(p.CustomerID) from Orders p inner join if (select count(p.CustomerID) from Orders p inner join inserted i on p.CustomerID=i.CustomerID)=1inserted i on p.CustomerID=i.CustomerID)=1
beginbegin
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 print 'Please give this customer a 10% discount on all purchases made today.'all purchases made today.'
endend
29
Invoking the Insert TriggerInvoking the Insert Trigger
Doing the following:Doing the following:insert into Orders (CustomerID, insert into Orders (CustomerID, EmployeeID, OrderDate) values (‘OU', 4, EmployeeID, OrderDate) values (‘OU', 4, 2000-7-24)2000-7-24)
Will result in:Will result in:This is first order placed by University.This is first order placed by University.
Please give this customer a 10% discount Please give this customer a 10% discount on all purchases made todayon all purchases made today..
Doing the following:Doing the following:insert into Orders (CustomerID, insert into Orders (CustomerID, EmployeeID, OrderDate) values (‘OU', 4, EmployeeID, OrderDate) values (‘OU', 4, 2000-7-24)2000-7-24)
Will result in:Will result in:This is first order placed by University.This is first order placed by University.
Please give this customer a 10% discount Please give this customer a 10% discount on all purchases made todayon all purchases made today..
30
A Delete TriggerA Delete Trigger(This trigger automatically increments the inventory in the Products table when an order is (This trigger automatically increments the inventory in the Products table when an order is
cancelled.)cancelled.)
create trigger DeleteOrderscreate trigger DeleteOrders
on [Order Details]on [Order Details]
for deletefor delete
asas
declare @units smallint, @prod char(2), @sunits declare @units smallint, @prod char(2), @sunits smallint, @funits smallintsmallint, @funits smallint
set @sunits=(select p.UnitsInStock set @sunits=(select p.UnitsInStock
from Products p inner join Deleted d from Products p inner join Deleted d
on p.ProductID=d.ProductID)on p.ProductID=d.ProductID)
set @units=(select d.Quantity from Deleted d)set @units=(select d.Quantity from Deleted d)
set @funits=@sunits+@unitsset @funits=@sunits+@units
set @prod=(select ProductID from deleted)set @prod=(select ProductID from deleted)
(This trigger automatically increments the inventory in the Products table when an order is (This trigger automatically increments the inventory in the Products table when an order is cancelled.)cancelled.)
create trigger DeleteOrderscreate trigger DeleteOrders
on [Order Details]on [Order Details]
for deletefor delete
asas
declare @units smallint, @prod char(2), @sunits declare @units smallint, @prod char(2), @sunits smallint, @funits smallintsmallint, @funits smallint
set @sunits=(select p.UnitsInStock set @sunits=(select p.UnitsInStock
from Products p inner join Deleted d from Products p inner join Deleted d
on p.ProductID=d.ProductID)on p.ProductID=d.ProductID)
set @units=(select d.Quantity from Deleted d)set @units=(select d.Quantity from Deleted d)
set @funits=@sunits+@unitsset @funits=@sunits+@units
set @prod=(select ProductID from deleted)set @prod=(select ProductID from deleted)
31
Delete Trigger (contd.)Delete Trigger (contd.)
beginbegin
update Products update Products
set UnitsInStock=@funits where ProductID=@prodset UnitsInStock=@funits where ProductID=@prod
print 'Updating inventory for '+convert(char(2),@prod)print 'Updating inventory for '+convert(char(2),@prod)
print 'Initial units in stock '+convert(char(2),@sunits)print 'Initial units in stock '+convert(char(2),@sunits)
print 'Restoring '+convert(char(2),@units)+' from print 'Restoring '+convert(char(2),@units)+' from cancelled order'cancelled order'
print 'Current units in stock '+convert(char(2),@funits)print 'Current units in stock '+convert(char(2),@funits)
endend
beginbegin
update Products update Products
set UnitsInStock=@funits where ProductID=@prodset UnitsInStock=@funits where ProductID=@prod
print 'Updating inventory for '+convert(char(2),@prod)print 'Updating inventory for '+convert(char(2),@prod)
print 'Initial units in stock '+convert(char(2),@sunits)print 'Initial units in stock '+convert(char(2),@sunits)
print 'Restoring '+convert(char(2),@units)+' from print 'Restoring '+convert(char(2),@units)+' from cancelled order'cancelled order'
print 'Current units in stock '+convert(char(2),@funits)print 'Current units in stock '+convert(char(2),@funits)
endend
32
Invoking the Delete TriggerInvoking the Delete Trigger
Doing the following:Doing the following:delete from [Order Details] where delete from [Order Details] where OrderID=11084OrderID=11084
Will result in:Will result in:Updating inventory for 11Updating inventory for 11
Initial units in stock 65Initial units in stock 65
Restoring 15 from cancelled orderRestoring 15 from cancelled order
Current units in stock 80Current units in stock 80
Doing the following:Doing the following:delete from [Order Details] where delete from [Order Details] where OrderID=11084OrderID=11084
Will result in:Will result in:Updating inventory for 11Updating inventory for 11
Initial units in stock 65Initial units in stock 65
Restoring 15 from cancelled orderRestoring 15 from cancelled order
Current units in stock 80Current units in stock 80
33
Another Insert TriggerAnother Insert Trigger
This trigger implements a new business rule requiring all order quantities to exceed 5 units.This trigger implements a new business rule requiring all order quantities to exceed 5 units.
create trigger InsertOrderDetailcreate trigger InsertOrderDetail
on [Order Details]on [Order Details]
for insertfor insert
asas
if (select Quantity from Inserted)<5if (select Quantity from Inserted)<5
beginbegin
print 'This is a wholesale business.'print 'This is a wholesale business.'
print 'All order quantities must be at print 'All order quantities must be at least least 5 units. '5 units. '
rollback transactionrollback transaction
endend
This trigger implements a new business rule requiring all order quantities to exceed 5 units.This trigger implements a new business rule requiring all order quantities to exceed 5 units.
create trigger InsertOrderDetailcreate trigger InsertOrderDetail
on [Order Details]on [Order Details]
for insertfor insert
asas
if (select Quantity from Inserted)<5if (select Quantity from Inserted)<5
beginbegin
print 'This is a wholesale business.'print 'This is a wholesale business.'
print 'All order quantities must be at print 'All order quantities must be at least least 5 units. '5 units. '
rollback transactionrollback transaction
endend
34
Invoking the TriggerInvoking the Trigger
Doing the following:Doing the following:insert into [order details] values (11084, 11, 14, 2, 0)
Will result in: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:Doing the following:insert into [order details] values (11084, 11, 14, 2, 0)
Will result in: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
Viewing Information on TriggersViewing Information on Triggers
• Listing of trigger codeSP_HELPTEXT triggername
• Listing objects referenced by triggerSP_DEPENDS triggername
• Listing triggers on a tableSP_HELPTRIGGER tablename
• Listing of trigger codeSP_HELPTEXT triggername
• Listing objects referenced by triggerSP_DEPENDS triggername
• Listing triggers on a tableSP_HELPTRIGGER tablename