Common SQL has three iteration constructs: ado-loop, a mapping function, and an extension to the Common Lisploop macro.
Macro
do-query &rest args query &key database &rest body
Function
map-query result-type function query-expression &key database
map function. Macro
loop macro has been extended with a clause for iterating over query results. The syntax of the new clause is:
{for|as} var [type-spec] being
{the|each}{tuples|tuple}
{in|of} query-expression
tuple is used so that it can also be applied to the object-oriented case. In the functional case,tuple is synonymous withrecord. loop macro, the new iteration clause provides an integrated report generation facility. map-query requires flatp to be specified; otherwise each name would be wrapped in a list.
(do-query ((name)[select [ename] :from [emp]])
(print name))
(map-query
nil
#'(lambda (name) (print name))
[select [ename] :from [emp] :flatp t])
(loop for (name)
being each tuple in
[select [ename] :from [emp]]
do
(print name))
loop example binds, on each record returned as a result of the query,name andsalary, accumulates the salary, and for salaries greater than 2750 increments a count, and prints the details. Finally, the average salary is printed.
(loop for (name salary) being each record in
[select [ename] [sal] :from [emp]]
initially (format t "~&~20A~10D" 'name 'salary)
when (and salary (> salary 2750))
count salary into salaries
and sum salary into total
and do (format t "~&~20A~10D" name salary)
else
do (format t "~&~20A~10D" name "N/A")
finally
(format t "~2&Av Salary: ~10D" (/ total salaries)))