You are on page 1of 1

96 Chapter 3: Selecting

3.7 SELECT FROM Procedure Call


A SQL Anywhere stored procedure can return a result set, and that result set can
be treated just like a table in a FROM clause.
<procedure_reference> ::= [ <owner_name> "." ] <procedure_name>
"(" [ <argument_list> ] ")"
[ WITH "(" <result_definition_list> ")" ]
[ [ AS ] <correlation_name> ]
<procedure_name> ::= <identifier>
<argument_list> ::= <argument> { "," <argument> }
<argument> ::= <basic_expression>
| <parameter_name> "=" <basic_expression>
<parameter_name> ::= see <parameter_name> in Chapter 8, Packaging
<result_definition_list> ::= <result_definition> { "," <result_definition> }
<result_definition> ::= <alias_name> <data_type>
<data_type> ::= see <data_type> in Chapter 1, Creating
The advantage to using a stored procedure is that it can contain multiple state-
ments whereas derived tables and views must be coded as a single query.
Sometimes a difficult problem is made easier by breaking it into separate steps.
For example, consider this convoluted request: Show all the products that con-
tributed to the second- and third-best sales for a single color on a single day in
the worst year for sales, using three of the ASADEMO database tables
described in the previous section product, sales_order, and
sales_order_items.
A divide-and-conquer approach can be used to solve this problem:
n First, compute the worst year for total sales.
n Second, within that year, find the second- and third-best sales for a single
color on a single day.
n Third, for those combinations of best color and order date, find the match-
ing products; in other words, find the products with matching colors that
were ordered on those dates.
Each of these steps has its challenges, but solving them separately is a lot easier
than writing one single select to solve them all at once. And even if you could
write one query to do everything, other people might have a lot of trouble
understanding what youve written, and in some shops maintainability is more
important than elegance.
A stored procedure called p_best_losers_in_worst_year performs the first
two steps: One SELECT computes the total sales for each year, sorts the results
in ascending order by sales amount, and takes the first year and stores it in a
local variable called @worst_year. A second SELECT computes the total sales
by color and date within @worst_year, sorts the results in descending order by
sales amount, and returns the second and third rows (the best losers) as the
procedure result set.
The following shows what the procedure looks like. For more information
about the CREATE PROCEDURE statement, see Section 8.9.
CREATE PROCEDURE p_best_losers_in_worst_year()
BEGIN
DECLARE @worst_year INTEGER;

You might also like