Diapositive 1 - ShareStudies.com

1
Advanced SQL
• Functions
• Procedural Constructs
• Triggers
Procedural Extensions and Stored Procedures
• SQL provides a module language
– Permits definition of procedures in SQL, with if-thenelse statements, for and while loops, etc.
• Stored Procedures
– Can store procedures in the database
– then execute them using the call statement
– permit external applications to operate on the database
without knowing about internal details
Functions and Procedures
• SQL supports functions and procedures
• Functions/procedures can be written in SQL itself, or in
an external programming language.
• Functions are particularly useful with specialized data
types such as images and geometric objects.
• Example: functions to check if polygons overlap, or
to compare images for similarity.
• Some database systems support table-valued
functions, which can return a relation as a result.
• SQL also supports a rich set of imperative constructs,
including
• Loops, if-then-else, assignment
SQL Functions
• Define a function that, given the name of a department, returns the
count of the number of instructors in that department.
create function dept_count (dept_name varchar(20))
returns integer
begin
declare d_count integer;
select count (* ) into d_count
from instructor
where instructor.dept_name = dept_name
return d_count;
end
• Find the department name and budget of all departments with more
that 12 instructors.
select dept_name, budget
from department
where dept_count (dept_name ) > 1
Table Functions
• SQL:2003 added functions that return a relation as a result
• Example: Return all accounts owned by a given customer
create function instructors_of (dept_name char(20)
returns table ( ID varchar(5),
name varchar(20),
dept_name varchar(20),
salary numeric(8,2))
return table
(select ID, name, dept_name, salary
from instructor
where instructor.dept_name = instructors_of.dept_name)
• Usage
select *
from table (instructors_of (‘Music’))
SQL Procedures
• The dept_count function could instead be written as procedure:
create procedure dept_count_proc (in dept_name varchar(20),
out d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name = dept_count_proc.dept_name
end
• Procedures can be invoked either from an SQL procedure or from
embedded SQL, using the call statement.
declare d_count integer;
call dept_count_proc( ‘Physics’, d_count);
Procedures and functions can be invoked also from dynamic SQL
• SQL allows more than one function/procedure of the same name (called
name overloading), as long as the number of
arguments differ, or at least the types of the arguments differ
Procedural Constructs
• Compound statement: begin … end,
– May contain multiple SQL statements between begin and end.
– Local variables can be declared within a compound statements
• While and repeat statements:
declare n integer default 0;
while n < 10 do
set n = n + 1
end while
repeat
set n = n – 1
until n = 0
end repeat
Procedural Constructs (Cont.)
• For loop
• Permits iteration over all results of a query
• Example:
declare n integer default 0;
for r as
select budget from department
where dept_name = ‘Music’
do
set n = n - r.budget
end for
Procedural Constructs (cont.)
• Conditional statements (if-then-else)
SQL also supports a case statement similar to C case statement
• Example procedure: registers student after ensuring classroom capacity
is not exceeded
– Returns 0 on success and -1 if capacity is exceeded
– See book for details
• Signaling of exception conditions, and declaring handlers for exceptions
declare out_of_classroom_seats condition
declare exit handler for out_of_classroom_seats
begin
…
.. signal out_of_classroom_seats
end
– The handler here is exit -- causes enclosing begin..end to be exited
– Other actions possible on exception
External Language Functions/Procedures
• SQL:1999 permits the use of functions and procedures written in other
languages such as C or C++
• Declaring external language procedures and functions
create procedure dept_count_proc(in dept_name varchar(20),
out count integer)
language C
external name ’ /usr/avi/bin/dept_count_proc’
create function dept_count(dept_name varchar(20))
returns integer
language C
external name ‘/usr/avi/bin/dept_count’
External Language Routines (Cont.)
• Benefits of external language functions/procedures:
– more efficient for many operations, and more expressive power.
• Drawbacks
– Code to implement function may need to be loaded into database
system and executed in the database system’s address space.
• risk of accidental corruption of database structures
• security risk, allowing users access to unauthorized data
– There are alternatives, which give good security at the cost of
potentially worse performance.
– Direct execution in the database system’s space is used when
efficiency is more important than security.
Triggers
• A trigger is a statement that is executed
automatically by the system as a side effect of a
modification to the database.
• To design a trigger mechanism, we must:
• Specify the conditions under which the trigger is
to be executed.
• Specify the actions to be taken when the trigger
executes.
• Triggers introduced to SQL standard in SQL:1999,
but supported even earlier using non-standard
syntax by most databases.
Triggers
• Tables can have multiple triggers.
• The CREATE TRIGGER statement can be defined with the FOR UPDATE,
FOR INSERT, or FOR DELETE clauses to target a trigger to a specific class
of data modification actions.
• When FOR UPDATE is specified, the IF UPDATE (column_name) clause
can be used to target a trigger to updates affecting a particular column.
• Types of trigger:
– After Trigger
– Multiple After Triggers
– Instead Of Triggers
– Mixing Triggers Type
Create Trigger
Example: we want to send an email to the Sales Manager when an order is entered
whose priority is high. When SQL is used to insert the Orders row, a trigger is used to
determine the OrderPriority and send the email when the criteria is met.
CREATE TABLE Orders (Ord_ID int IDENTITY, Ord_Priority varchar(10))
go
CREATE TRIGGER tr_Orders_INSERT
ON Orders
FOR INSERT
AS IF (SELECT COUNT(*) FROM inserted WHERE Ord_Priority = 'High') = 1
BEGIN
PRINT 'Email Code Goes Here'
END
go
INSERT Orders (Ord_Priority) VALUES ('High')
Update Trigger
An UPDATE trigger is used to perform an action after an update is made on a table
CREATE TRIGGER tr_Orders_UPDATE
ON Orders
AFTER UPDATE AS
--Make sure Priority was changed
IF NOT UPDATE(Ord_Priority)
RETURN
--Determine if Priority was changed to high
IF EXISTS (SELECT * FROM inserted a JOIN deleted b ON a.Ord_ID=b.Ord_ID
WHERE b.Ord_Priority <> 'High' AND a.Ord_Priority = 'High')
BEGIN
DECLARE @Count tinyint
SET @Count = (SELECT COUNT(*) FROM inserted a JOIN deleted b ON a.Ord_ID=b.Ord_ID
WHERE b.Ord_Priority <> 'High' AND a.Ord_Priority = 'High')
PRINT CAST(@Count as varchar(3))+' row(s) where changed to a priority of High'
END
go
Delete Trigger
The example here simply counts the number of rows in the deleted table to see how many
had a priority of high
CREATE TRIGGER tr_Orders_DELETE
ON Orders
AFTER DELETE AS
--Determine if Order with a Priority of High was deleted
IF EXISTS (SELECT * FROM deleted WHERE Ord_Priority = 'High')
BEGIN
DECLARE @Count tinyint
SET @Count = (SELECT * FROM deleted WHERE Ord_Priority = 'High')
PRINT CAST(@Count as varchar(3))+' row(s) where deleted whose priority was High'
END
go
Instead of Trigger
•
An INSTEAD OF Trigger is used to perform an action instead of the one that
caused the trigger to be fired.
•
If we have an INSTEAD OF INSERT trigger defined on a table and an INSERT is
executed. A row is not added to the table, but the code in the trigger is fired.
CREATE TRIGGER tr_Orders_INSERT_InsteadOf
ON Orders
INSTEAD OF INSERT
AS
PRINT 'Updateable Views are Messy'
go
Instead of Trigger
• INSTEAD-OF triggers are very powerful objects in SQL Server.
• They allow the developer to divert the database engine to do
something different than what the user is trying to do.
• An example of this would be to add an INSTEAD-OF trigger to any
table in your database that rolls back transactions on tables that
you do not want modified.
• We must be careful when using this method because the
INSTEAD-OF trigger will need to be disabled before any specified
modifications can occur to this table.
After versus Instead of Triggers
When should we use an AFTER trigger vs. INSTEAD OF trigger?
• If the data modification will always happen - AFTER trigger.
• If the data modification will never happen - INSTEAD OF
trigger.
• If the data modification will happen more often than the
alternate code - AFTER trigger.
• If the data modification will happen less often than the
alternate code - INSTEAD OF trigger.