22 Using cursors

 

In chapter 21, we explored making decisions in queries and learned how to make conditional evaluations. Using IF and THEN keywords allowed us to evaluate one or more values and then decide whether to do something else, such as insert a row of values into a table.

In this chapter, we’ll look at other ways to evaluate data and make decisions in SQL, focusing primarily on cursors. Cursors enable us to evaluate a set of data one row or value at a time. Also, as we’ll see, they have a bit of complexity, and there are important considerations regarding their use.

The use of cursors in MySQL is restricted to database objects containing prepared SQL, such as stored procedures. Because of this restriction, we’ll look at some previously undiscussed features of variables and parameters before we dive into creating and using cursors.

22.1 Reviewing variables and parameters

We’ve used variables since chapter 13 and parameters since chapter 20. Although variables and parameters are similar in that they’re placeholders for values, they have different properties relative to their use. The following sections show how we can use some of these properties.

22.1.1 Variables inside stored procedures

Chapter 13 briefly mentioned the way variables are declared in MySQL and how they differ in other relational database management systems (RDBMSes). In case you don’t remember, here’s the warning from that chapter:

22.1.2 Output parameters

22.2 Cursors

22.2.1 Anatomy of a cursor

22.2.2 Creating a cursor

22.3 Alternatives to cursors

22.3.1 Using WHILE

22.3.2 Temporary tables

22.4 Considerations for using cursors

22.4.1 Thinking in sets

22.4.2 Thinking about cursor use

22.5 Lab

22.6 Lab answers