SQL Stored Procedures: Winter 2006-2007
SQL Stored Procedures: Winter 2006-2007
SQL Stored Procedures: Winter 2006-2007
Winter 2006-2007
Lecture 10
SQL Functions
• SQL queries can use sophisticated math
operations and functions
– Can compute simple functions, aggregates
– Can compute and filter results
• Applications often require specialized
computations
– Would like to use these in SQL queries, too
• SQL provides a mechanism for defining
functions
– Called User-Defined Functions (UDFs)
SQL Functions (2)
• Can be defined in a procedural SQL language,
or in an external language
– SQL:1999, SQL:2003 both specify a language for
declaring functions and procedures
– Different vendors provide their own languages
• Oracle: PL/SQL
• Microsoft: TransactSQL
• PostgreSQL: PL/pgSQL
• MySQL: new stored procedure support strives to follow
specifications (and mostly does)
• Some also support external languages: Java, C, etc.
– Lots of variation in features and support (as usual)
Example SQL Function
• A SQL function to count how many bank accounts a
particular customer has:
CREATE FUNCTION
account_count(customer_name VARCHAR(20))
RETURNS INTEGER
BEGIN
DECLARE a_count INTEGER;
SELECT COUNT(*) INTO a_count
FROM depositor
WHERE depositor.customer_name = customer_name;
RETURN a_count;
END
– Function can take arguments and return values
– Use SQL statements and other operations in body
Example SQL Function (2)
• Can use our function for individual accounts:
SELECT account_count('Johnson');
OPEN cur;
REPEAT
FETCH cur INTO bal;
IF NOT done THEN
SET total = total + bal;
END IF;
UNTIL done END REPEAT;
CLOSE cur;
RETURN total;
END
Using Our Stored Procedure
• Can compute total balances now:
SELECT customer_name,
acct_total(customer_name) AS total
FROM customer; +---------------+---------+
| customer_name | total |
+---------------+---------+
– Result: | Adams | 0.00 |
| Brooks | 0.00 |
| Curry | 0.00 |
| Glenn | 0.00 |
| Green | 0.00 |
| Hayes | 900.00 |
| Jackson | 0.00 |
| Johnson | 1400.00 |
| Jones | 750.00 |
| Lindsay | 700.00 |
| Majeris | 850.00 |
| McBride | 0.00 |
| Smith | 1325.00 |
| Turner | 350.00 |
| Williams | 0.00 |
+---------------+---------+
Stored Procedure Benefits
• Very effective for manipulating large datasets
within the database
– Don’t incur communications overhead
– Database is designed for such tasks, but applications
and languages typically aren’t
• Often used to provide secure interface to data
– Banks will lock down data, and only expose
operations through stored procedures
• Can encapsulate business logic in procedures
– Forbid invalid states by requiring all operations go
through stored procedures
Stored Procedure Drawbacks
• Increases load on database system
– Can reduce performance for all operations
being performed by DBMS
– Need to make sure the operation really
requires a stored procedure…
• Hard to migrate to a different DBMS
– Different vendors’ procedural languages have
many distinct features and limitations