Snowflake SQL Tutorial 148 - My Cursor Walked Once And Then Gave Me Nothing

Snowflake SQL · Episode 148

In this post we are going to cover cursors and RESULTSETs in Snowflake Scripting.

Both of them let a block take a query and walk it row by row. A cursor is the familiar one, with OPEN, FETCH and CLOSE. A RESULTSET holds a query's rows and can be handed straight back to the caller.

And both of them will walk a query exactly once. That is the thing worth knowing about them, and each one has its own way of starting over.

We will start with the smallest cursor there is and build it up step by step. Every loop you will see is bounded by a guard, because that is how they actually ran. Every query was run on a real Snowflake account, and every result you see is the output it gave back.

Episode 148 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.

Let's create some sample data

We need something for the cursors to walk, and somewhere for a loop to write to later on. The script below makes both.

Sample data
-- Sample data for this post.
-- Six sales rows for the cursors to walk, and a table for a loop to write to.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;

CREATE OR REPLACE TABLE SALES_T148 (
    SALE_ID INT,
    REGION  VARCHAR(10),
    AMOUNT  NUMBER(10,2)
);

INSERT INTO SALES_T148 (SALE_ID, REGION, AMOUNT) VALUES
    (1, 'north', 100.00),
    (2, 'south', 250.50),
    (3, 'east',   75.25),
    (4, 'west',  310.00),
    (5, 'north',  45.00),
    (6, 'south',  88.25);

CREATE OR REPLACE TABLE TRACE_T148 (
    STEP INT,
    NOTE VARCHAR(60)
);
The insert
INSERT INTO SALES_T148 (SALE_ID, REGION, AMOUNT)
VALUES (1, 'north', 100.00), (2, 'south', 250.50),
       (3, 'east',   75.25), (4, 'west',  310.00),
       (5, 'north',  45.00), (6, 'south',  88.25);
Result1 row · 1 column
number of rows inserted
6

And here is what that leaves in the sales table, because the row count matters in two sections further down.

Query
SELECT COUNT(*) AS HOW_MANY, SUM(AMOUNT) AS TOTAL_AMOUNT FROM SALES_T148;
Result1 row · 2 columns
HOW_MANYTOTAL_AMOUNT
6869.00

Six rows. Now let's walk them.

Let's start with a cursor and a FOR loop

A cursor is declared with the query it is for, and the simplest way to walk it is a FOR loop. Read this body before we run it, because of what is missing from it.

Create
CREATE OR REPLACE PROCEDURE CURFOR_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1       CURSOR FOR SELECT SALE_ID, REGION FROM SALES_T148 ORDER BY SALE_ID;
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    FOR R IN C1 DO
        OUT_TEXT := :OUT_TEXT || R.SALE_ID || '=' || R.REGION || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN 'walked ' || :GUARD || ': ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function CURFOR_T148 successfully created.

There is no OPEN anywhere in there. Let's call it anyway.

Call
CALL CURFOR_T148();
Result1 row · 1 column
CURFOR_T148
walked 6: 1=north 2=south 3=east 4=west 5=north 6=south

Every row, in order, with both columns read off the loop variable. The FOR loop opened the cursor for us.

So does an explicit OPEN change anything?

Here is the same thing with an OPEN written in front of the loop.

Create
CREATE OR REPLACE PROCEDURE CUROPENFOR_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1       CURSOR FOR SELECT SALE_ID, REGION FROM SALES_T148 ORDER BY SALE_ID;
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    OPEN C1;
    FOR R IN C1 DO
        OUT_TEXT := :OUT_TEXT || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    CLOSE C1;
    RETURN 'walked ' || :GUARD || ': ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function CUROPENFOR_T148 successfully created.
Call
CALL CUROPENFOR_T148();
Result1 row · 1 column
CUROPENFOR_T148
walked 6: 1 2 3 4 5 6

The same row count, reported the same way. Saying OPEN yourself costs nothing and changes nothing, so write it if it makes the body easier to read.

What does the row object actually know?

Inside the loop, R is a row object and we ask it for columns by name. So what name does it use when the cursor's query renames one?

Create
CREATE OR REPLACE PROCEDURE CURALIAS_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1       CURSOR FOR SELECT SALE_ID AS THE_ID, AMOUNT AS THE_AMOUNT
                        FROM SALES_T148 WHERE SALE_ID <= 2 ORDER BY SALE_ID;
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    FOR R IN C1 DO
        OUT_TEXT := :OUT_TEXT || R.THE_ID || '/' || R.THE_AMOUNT || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN 'by alias: ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function CURALIAS_T148 successfully created.
Call
CALL CURALIAS_T148();
Result1 row · 1 column
CURALIAS_T148
by alias: 1/100.00 2/250.50

The row uses the alias, not the name the column has in the table.

Which raises the obvious question. What if we ask it for a column the query never selected at all?

Create
CREATE OR REPLACE PROCEDURE CURNOCOL_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1       CURSOR FOR SELECT SALE_ID FROM SALES_T148 WHERE SALE_ID = 1;
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    FOR R IN C1 DO
        OUT_TEXT := :OUT_TEXT || R.REGION;
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN 'got: ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function CURNOCOL_T148 successfully created.

Created without a word of complaint, which is worth noticing. Now let's call it.

Call
CALL CURNOCOL_T148();
Query failed — Snowflake returned an error
100183 (P0000): Uncaught exception of type 'EXPRESSION_ERROR' on line 8 at position 33 : Given column name/index does not exist: REGION

100183, the given column name does not exist. That is at call time, not at create time, so a typo in a field name sits there quietly until somebody runs the procedure.

Now let's take one row at a time with FETCH

A FOR loop is not the only way to walk a cursor. We can open it ourselves and pull one row at a time with FETCH, stopping when the variable comes back null.

Create
CREATE OR REPLACE PROCEDURE CURFETCH_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1       CURSOR FOR SELECT SALE_ID FROM SALES_T148 ORDER BY SALE_ID;
    THE_ID   NUMBER;
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    OPEN C1;
    LOOP
        FETCH C1 INTO THE_ID;
        GUARD := :GUARD + 1;
        IF (:THE_ID IS NULL) THEN BREAK; END IF;
        OUT_TEXT := :OUT_TEXT || :THE_ID || ' ';
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END LOOP;
    CLOSE C1;
    RETURN 'after ' || :GUARD || ' fetches: ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function CURFETCH_T148 successfully created.
Call
CALL CURFETCH_T148();
Result1 row · 1 column
CURFETCH_T148
after 7 fetches: 1 2 3 4 5 6

Read that carefully, because there are two numbers in it. The cursor had six rows and the loop fetched seven times.

The seventh fetch is the one that found nothing and left the variable null, which is exactly how the loop knew to stop. So fetching past the end of a cursor is not an error.

Let's ask the same question with a WHILE loop instead of a LOOP, to be sure that is not an artefact of how the loop was written.

Create
CREATE OR REPLACE PROCEDURE CURFETCHWHILE_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1       CURSOR FOR SELECT SALE_ID FROM SALES_T148 ORDER BY SALE_ID;
    THE_ID   NUMBER  DEFAULT 0;
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    OPEN C1;
    WHILE (:GUARD < 10) DO
        FETCH C1 INTO THE_ID;
        GUARD := :GUARD + 1;
        IF (:THE_ID IS NULL) THEN BREAK; END IF;
        OUT_TEXT := :OUT_TEXT || :THE_ID || ' ';
    END WHILE;
    CLOSE C1;
    RETURN 'after ' || :GUARD || ' fetches: ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function CURFETCHWHILE_T148 successfully created.
Call
CALL CURFETCHWHILE_T148();
Result1 row · 1 column
CURFETCHWHILE_T148
after 7 fetches: 1 2 3 4 5 6

Word for word the same answer.

And FETCH can fill more than one variable at once, in the order the query selected them.

Create
CREATE OR REPLACE PROCEDURE CURFETCH2_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1       CURSOR FOR SELECT SALE_ID, REGION FROM SALES_T148 ORDER BY SALE_ID;
    THE_ID   NUMBER;
    THE_REG  VARCHAR;
BEGIN
    OPEN C1;
    FETCH C1 INTO THE_ID, THE_REG;
    CLOSE C1;
    RETURN 'first row: ' || :THE_ID || ' ' || :THE_REG;
END;
$$;
Result1 row · 1 column
status
Function CURFETCH2_T148 successfully created.
Call
CALL CURFETCH2_T148();
Result1 row · 1 column
CURFETCH2_T148
first row: 1 north

Two opposite mistakes with one error code

First, FETCH without opening the cursor.

Create
CREATE OR REPLACE PROCEDURE CURNOOPEN_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1     CURSOR FOR SELECT SALE_ID FROM SALES_T148 ORDER BY SALE_ID;
    THE_ID NUMBER;
BEGIN
    FETCH C1 INTO THE_ID;
    RETURN 'got ' || COALESCE(:THE_ID::VARCHAR, 'NULL');
END;
$$;
Result1 row · 1 column
status
Function CURNOOPEN_T148 successfully created.
Call
CALL CURNOOPEN_T148();
Query failed — Snowflake returned an error
092201 (P0000): CURSOR C1 is not open

092201, the cursor is not open. So OPEN is optional in front of a FOR loop and mandatory in front of a FETCH.

Now the opposite mistake. Closing one that was never opened.

Create
CREATE OR REPLACE PROCEDURE CURCLOSE_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1 CURSOR FOR SELECT SALE_ID FROM SALES_T148 WHERE SALE_ID = 1;
BEGIN
    CLOSE C1;
    RETURN 'closed it anyway';
END;
$$;
Result1 row · 1 column
status
Function CURCLOSE_T148 successfully created.
Call
CALL CURCLOSE_T148();
Query failed — Snowflake returned an error
092201 (P0000): Uncaught exception of type 'STATEMENT_ERROR' on line 5 at position 4 : CURSOR C1 is not open

The same code and the same sentence, although this one arrives wrapped in an uncaught statement error with a line number in front of it. Two opposite mistakes, one explanation: a cursor that is not open cannot be used for anything.

Can the cursor's query take a value from the block?

It can, and the spelling is particular. A question mark goes in the query, and the value is supplied when the cursor is opened.

Create
CREATE OR REPLACE PROCEDURE CURBIND_T148(CUTOFF NUMBER)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1       CURSOR FOR SELECT SALE_ID FROM SALES_T148 WHERE AMOUNT > ?
                        ORDER BY SALE_ID;
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    OPEN C1 USING (CUTOFF);
    FOR R IN C1 DO
        OUT_TEXT := :OUT_TEXT || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    CLOSE C1;
    RETURN 'over the cutoff: ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function CURBIND_T148 successfully created.
Call
CALL CURBIND_T148(100);
Result1 row · 1 column
CURBIND_T148
over the cutoff: 2 4

Two rows over the cutoff we passed in. OPEN ... USING bound the question mark, exactly as a bind works anywhere else.

Now the spelling you would reach for first: a colon variable inside the cursor's query, with no USING.

Create
CREATE OR REPLACE PROCEDURE CURCOLON_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    CUTOFF   NUMBER  DEFAULT 100;
    C1       CURSOR FOR SELECT SALE_ID FROM SALES_T148 WHERE AMOUNT > :CUTOFF
                        ORDER BY SALE_ID;
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    FOR R IN C1 DO
        OUT_TEXT := :OUT_TEXT || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN 'over the cutoff: ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function CURCOLON_T148 successfully created.
Call
CALL CURCOLON_T148();
Query failed — Snowflake returned an error
002049 (42601): Uncaught exception of type 'STATEMENT_ERROR' on line 9 at position 4 : SQL compilation error: error line 1 at position 46
Bind variable :CUTOFF not set.

002049, bind variable not set. So the colon that worked everywhere else in the last post does not work here.

Now the question to ask of any cursor: when does it decide?

A cursor is declared in one place and walked in another, so there is a window in between. Which moment fixes the rows it will see?

This body answers it. The cursor looks for a high sale id that does not exist yet. Then it opens. Then it inserts exactly such a row. Then it walks.

Create
CREATE OR REPLACE PROCEDURE CURSNAPSHOT_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1       CURSOR FOR SELECT SALE_ID FROM SALES_T148 WHERE SALE_ID >= 90
                        ORDER BY SALE_ID;
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    OPEN C1;
    INSERT INTO SALES_T148 (SALE_ID, REGION, AMOUNT) VALUES (91, 'late', 1.00);
    FOR R IN C1 DO
        OUT_TEXT := :OUT_TEXT || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    CLOSE C1;
    RETURN 'the cursor saw ' || :GUARD || ' rows: ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function CURSNAPSHOT_T148 successfully created.
Call
CALL CURSNAPSHOT_T148();
Result1 row · 1 column
CURSNAPSHOT_T148
the cursor saw 0 rows:

The cursor saw nothing. So is the row actually in the table?

Query
SELECT COUNT(*) AS LATE_ROWS FROM SALES_T148 WHERE SALE_ID = 91;
Result1 row · 1 column
LATE_ROWS
1

It is. Which answers the question: OPEN is the moment that fixes what the cursor will see. Anything that arrives afterwards is invisible to it, even when the same block put it there.

And three more cursor cases worth having seen

First, a cursor whose query matches nothing, walked with a FOR loop.

Create
CREATE OR REPLACE PROCEDURE CUREMPTY_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1    CURSOR FOR SELECT SALE_ID FROM SALES_T148 WHERE SALE_ID = 999;
    GUARD NUMBER DEFAULT 0;
BEGIN
    FOR R IN C1 DO
        GUARD := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN 'the body ran ' || :GUARD || ' times';
END;
$$;
Result1 row · 1 column
status
Function CUREMPTY_T148 successfully created.
Call
CALL CUREMPTY_T148();
Result1 row · 1 column
CUREMPTY_T148
the body ran 0 times

The body ran no times at all. Not an error, and not one pass with an empty row.

Next, a cursor over a table that does not exist. This one is created without a word of complaint as well.

Create
CREATE OR REPLACE PROCEDURE CURNOTABLE_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1    CURSOR FOR SELECT SALE_ID FROM NO_SUCH_TABLE_T148;
    GUARD NUMBER DEFAULT 0;
BEGIN
    FOR R IN C1 DO
        GUARD := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN 'walked ' || :GUARD;
END;
$$;
Result1 row · 1 column
status
Function CURNOTABLE_T148 successfully created.
Call
CALL CURNOTABLE_T148();
Query failed — Snowflake returned an error
002003 (42S02): Uncaught exception of type 'STATEMENT_ERROR' on line 6 at position 4 : SQL compilation error:
Object 'NO_SUCH_TABLE_T148' does not exist or not authorized. This executable runs with owner's rights. The owner role ACCOUNTADMIN must have at least one privilege granted on TABLE NO_SUCH_TABLE_T148.

002003 at call time, and read the rest of that message. It tells us the body runs with the owner's rights, which is why the name is resolved when the procedure runs rather than when it is written.

And last, LET in the middle of a block instead of a DECLARE section.

Create
CREATE OR REPLACE PROCEDURE CURLET_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
    LET C1 CURSOR FOR SELECT SALE_ID FROM SALES_T148 WHERE SALE_ID = 1;
    LET OUT_TEXT VARCHAR := '';
    LET GUARD NUMBER := 0;
    FOR R IN C1 DO
        OUT_TEXT := :OUT_TEXT || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN 'walked: ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function CURLET_T148 successfully created.
Call
CALL CURLET_T148();
Result1 row · 1 column
CURLET_T148
walked: 1

LET declares a cursor just as happily as DECLARE does.

Now the other one: a RESULTSET

A RESULTSET holds a query's rows. We met it in the stored procedures post, where it was handed back to the caller with RETURN TABLE.

Create
CREATE OR REPLACE PROCEDURE RSTABLE_T148()
RETURNS TABLE (SALE_ID INT, THE_AMOUNT NUMBER(10,2))
LANGUAGE SQL
AS
$$
DECLARE
    RS RESULTSET;
BEGIN
    RS := (SELECT SALE_ID, AMOUNT FROM SALES_T148 WHERE SALE_ID <= 3
           ORDER BY SALE_ID);
    RETURN TABLE(RS);
END;
$$;
Result1 row · 1 column
status
Function RSTABLE_T148 successfully created.
Call
CALL RSTABLE_T148();
Result3 rows · 2 columns
SALE_IDTHE_AMOUNT
1100.00
2250.50
375.25

That still works. But a RESULTSET can also be walked directly, and this is the part that surprised me. Look at the FOR loop in this one: there is no cursor in it anywhere.

Create
CREATE OR REPLACE PROCEDURE RSDIRECT_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    RS       RESULTSET DEFAULT (SELECT SALE_ID FROM SALES_T148 WHERE SALE_ID <= 3
                                ORDER BY SALE_ID);
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    FOR R IN RS DO
        OUT_TEXT := :OUT_TEXT || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN 'walked ' || :GUARD || ': ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function RSDIRECT_T148 successfully created.
Call
CALL RSDIRECT_T148();
Result1 row · 1 column
RSDIRECT_T148
walked 3: 1 2 3

A FOR loop takes a RESULTSET on its own.

And it goes the other way too. We can build a cursor from a RESULTSET. Notice where that RESULTSET got its query: on the declaration, as a DEFAULT.

Create
CREATE OR REPLACE PROCEDURE RSCURSOR_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    RS       RESULTSET DEFAULT (SELECT SALE_ID FROM SALES_T148 WHERE SALE_ID <= 3
                                ORDER BY SALE_ID);
    C1       CURSOR FOR RS;
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    OPEN C1;
    FOR R IN C1 DO
        OUT_TEXT := :OUT_TEXT || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    CLOSE C1;
    RETURN 'walked ' || :GUARD || ': ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function RSCURSOR_T148 successfully created.
Call
CALL RSCURSOR_T148();
Result1 row · 1 column
RSCURSOR_T148
walked 3: 1 2 3

So the two travel in both directions and you can use whichever reads better.

One thing a RESULTSET does need is a query in it. Here is one declared with no default and never assigned anything either.

Create
CREATE OR REPLACE PROCEDURE RSUNSET_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    RS       RESULTSET;
    GUARD    NUMBER DEFAULT 0;
BEGIN
    FOR R IN RS DO
        GUARD := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN 'walked ' || :GUARD;
END;
$$;
Result1 row · 1 column
status
Function RSUNSET_T148 successfully created.
Call
CALL RSUNSET_T148();
Query failed — Snowflake returned an error
092212 (P0000): Uncaught exception of type 'STATEMENT_ERROR' on line 0 at position -1 : Stored procedure execution error: uninitialized resultSet 'RS'

092212, uninitialised result set. Which is fair enough.

So how do you count the rows in a RESULTSET?

This is a reasonable thing to want and the obvious way does not work. The obvious way is to select from it, the way you would from any table function.

Create
CREATE OR REPLACE PROCEDURE RSCOUNT_T148()
RETURNS NUMBER
LANGUAGE SQL
AS
$$
DECLARE
    RS      RESULTSET DEFAULT (SELECT SALE_ID FROM SALES_T148 WHERE SALE_ID <= 3);
    HOW_MANY NUMBER;
BEGIN
    SELECT COUNT(*) INTO :HOW_MANY FROM TABLE(RS);
    RETURN :HOW_MANY;
END;
$$;
Query failed — Snowflake returned an error
001003 (42000): SQL compilation error:
syntax error line 6 at position 48 unexpected ')'.
syntax error line 6 at position 49 unexpected ';'.

001003, a syntax error. So that is the CREATE failing, which means the procedure was never made at all.

Call
CALL RSCOUNT_T148();
Query failed — Snowflake returned an error
002139 (02000): SQL compilation error:
Unknown function RSCOUNT_T148.

Unknown function, which only confirms it. There was never anything there to call.

And RESULT_SCAN will not take one either, because it wants a query id and a RESULTSET is not one.

Create
CREATE OR REPLACE PROCEDURE RSCOUNTSCAN_T148B()
RETURNS NUMBER
LANGUAGE SQL
AS
$$
DECLARE
    RS       RESULTSET DEFAULT (SELECT SALE_ID FROM SALES_T148B
                                WHERE SALE_ID <= 3 ORDER BY SALE_ID);
    HOW_MANY NUMBER;
BEGIN
    SELECT COUNT(*) INTO :HOW_MANY
    FROM TABLE(RESULT_SCAN(RS));
    RETURN :HOW_MANY;
END;
$$;
Result1 row · 1 column
status
Function RSCOUNTSCAN_T148B successfully created.
Call
CALL RSCOUNTSCAN_T148B();
Query failed — Snowflake returned an error
001095 (22023): Uncaught exception of type 'STATEMENT_ERROR' on line 7 at position 4 : SQL compilation error: error line 2 at position 27
Invalid result query ID, found 'RS'

001095, invalid result query id. So here are the two ways that do work. The first is to walk it and count the passes as you go.

Create
CREATE OR REPLACE PROCEDURE RSCOUNTLOOP_T148B()
RETURNS NUMBER
LANGUAGE SQL
AS
$$
DECLARE
    RS       RESULTSET DEFAULT (SELECT SALE_ID FROM SALES_T148B
                                WHERE SALE_ID <= 3 ORDER BY SALE_ID);
    HOW_MANY NUMBER DEFAULT 0;
BEGIN
    FOR R IN RS DO
        HOW_MANY := :HOW_MANY + 1;
        IF (:HOW_MANY >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN :HOW_MANY;
END;
$$;
Result1 row · 1 column
status
Function RSCOUNTLOOP_T148B successfully created.
Call
CALL RSCOUNTLOOP_T148B();
Result1 row · 1 column
RSCOUNTLOOP_T148B
3

That is the straightforward answer and it is the one I would use.

The other is to hand the rows back and let the next statement do the counting.

Create
CREATE OR REPLACE PROCEDURE RSHANDBACK_T148B()
RETURNS TABLE (SALE_ID INT)
LANGUAGE SQL
AS
$$
DECLARE
    RS RESULTSET DEFAULT (SELECT SALE_ID FROM SALES_T148B
                          WHERE SALE_ID <= 3 ORDER BY SALE_ID);
BEGIN
    RETURN TABLE(RS);
END;
$$;
Result1 row · 1 column
status
Function RSHANDBACK_T148B successfully created.
Call
CALL RSHANDBACK_T148B();
Result3 rows · 1 column
SALE_ID
1
2
3
Query
SELECT COUNT(*) AS HOW_MANY FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 1 column
HOW_MANY
3

Same answer, arrived at from outside the procedure rather than inside it.

Now the thing this post is really about

Here is a block with two FOR loops in it, one after the other, over the same RESULTSET. The first loop labels what it sees with an a and the second with a b, so we can tell them apart in the answer.

Create
CREATE OR REPLACE PROCEDURE RSTWICE_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    RS       RESULTSET DEFAULT (SELECT SALE_ID FROM SALES_T148 WHERE SALE_ID <= 2
                                ORDER BY SALE_ID);
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    FOR R IN RS DO
        OUT_TEXT := :OUT_TEXT || 'a' || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    FOR R IN RS DO
        OUT_TEXT := :OUT_TEXT || 'b' || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN 'two passes gave: ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function RSTWICE_T148 successfully created.
Call
CALL RSTWICE_T148();
Result1 row · 1 column
RSTWICE_T148
two passes gave: a1 a2

Two values from the first loop, and then nothing. The second loop got no rows at all.

Let's ask the same question of a cursor. Two loops, back to back, over one cursor, labelled the same way.

Create
CREATE OR REPLACE PROCEDURE CURREOPEN_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1       CURSOR FOR SELECT SALE_ID FROM SALES_T148 WHERE SALE_ID <= 2
                        ORDER BY SALE_ID;
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    FOR R IN C1 DO
        OUT_TEXT := :OUT_TEXT || 'a' || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    FOR R IN C1 DO
        OUT_TEXT := :OUT_TEXT || 'b' || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN 'two passes gave: ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function CURREOPEN_T148 successfully created.
Call
CALL CURREOPEN_T148();
Result1 row · 1 column
CURREOPEN_T148
two passes gave: a1 a2

Exactly the same. Both of them walk once and then they are done, and neither of them says a word about it. The second loop is not an error. It simply has nothing to do.

So how do you get a second pass?

Each one rewinds, and each one rewinds differently. For a RESULTSET, you give it its query again.

Create
CREATE OR REPLACE PROCEDURE RSREWIND_T148B()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    RS       RESULTSET;
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    RS := (SELECT SALE_ID FROM SALES_T148B WHERE SALE_ID <= 2 ORDER BY SALE_ID);
    FOR R IN RS DO
        OUT_TEXT := :OUT_TEXT || 'a' || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RS := (SELECT SALE_ID FROM SALES_T148B WHERE SALE_ID <= 2 ORDER BY SALE_ID);
    FOR R IN RS DO
        OUT_TEXT := :OUT_TEXT || 'b' || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN 'two passes gave: ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function RSREWIND_T148B successfully created.
Call
CALL RSREWIND_T148B();
Result1 row · 1 column
RSREWIND_T148B
two passes gave: a1 a2 b1 b2

All four labels this time, so both loops walked. Assigning the RESULTSET again rewound it.

For a cursor the answer is different: close it, then open it again.

Create
CREATE OR REPLACE PROCEDURE CURREWIND_T148B()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1       CURSOR FOR SELECT SALE_ID FROM SALES_T148B WHERE SALE_ID <= 2
                        ORDER BY SALE_ID;
    OUT_TEXT VARCHAR DEFAULT '';
    GUARD    NUMBER  DEFAULT 0;
BEGIN
    OPEN C1;
    FOR R IN C1 DO
        OUT_TEXT := :OUT_TEXT || 'a' || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    CLOSE C1;
    OPEN C1;
    FOR R IN C1 DO
        OUT_TEXT := :OUT_TEXT || 'b' || R.SALE_ID || ' ';
        GUARD    := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    CLOSE C1;
    RETURN 'two passes gave: ' || :OUT_TEXT;
END;
$$;
Result1 row · 1 column
status
Function CURREWIND_T148B successfully created.
Call
CALL CURREWIND_T148B();
Result1 row · 1 column
CURREWIND_T148B
two passes gave: a1 a2 b1 b2

The same result by a different mechanism. Neither one rewinds by itself, and neither one will tell you it needs to.

One last thing: writing a row on every pass

This is the mistake I would have made, and did. Here is a cursor loop that inserts a row for every row it walks, using the row object's fields directly in the INSERT.

Create
CREATE OR REPLACE PROCEDURE CURDML_T148()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1    CURSOR FOR SELECT SALE_ID, REGION FROM SALES_T148 WHERE SALE_ID <= 3
                     ORDER BY SALE_ID;
    GUARD NUMBER DEFAULT 0;
BEGIN
    FOR R IN C1 DO
        INSERT INTO TRACE_T148 (STEP, NOTE)
            VALUES (R.SALE_ID, 'walked ' || R.REGION);
        GUARD := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN 'wrote ' || :GUARD || ' rows';
END;
$$;
Result1 row · 1 column
status
Function CURDML_T148 successfully created.
Call
CALL CURDML_T148();
Query failed — Snowflake returned an error
000904 (42000): Uncaught exception of type 'STATEMENT_ERROR' on line 8 at position 8 : SQL compilation error: error line 2 at position 20
invalid identifier 'R.SALE_ID'

000904, invalid identifier, and the name it cannot resolve is the row object's own field. Read where that is: the field reads perfectly well in an expression, and inside the INSERT it does not resolve at all.

And the table is untouched, because nothing ever got as far as being written.

Query
SELECT STEP, NOTE FROM TRACE_T148 ORDER BY STEP;
Result0 rows · 2 columns
STEPNOTE

An empty result. Now let's fix it. I re-ran this part on its own table so the two attempts could not be confused with each other.

Create
CREATE OR REPLACE TABLE SALES_T148B (
    SALE_ID INT,
    REGION  VARCHAR(10),
    AMOUNT  NUMBER(10,2)
);
Result1 row · 1 column
status
Table SALES_T148B successfully created.
Insert
INSERT INTO SALES_T148B (SALE_ID, REGION, AMOUNT)
VALUES (1, 'north', 100.00), (2, 'south', 250.50),
       (3, 'east',   75.25), (4, 'west',  310.00);
Result1 row · 1 column
number of rows inserted
4
Create
CREATE OR REPLACE TABLE TRACE_T148B (
    STEP INT,
    NOTE VARCHAR(60)
);
Result1 row · 1 column
status
Table TRACE_T148B successfully created.

The fix is to copy the field into a variable first and insert the variable.

Create
CREATE OR REPLACE PROCEDURE CURDML_T148B()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1       CURSOR FOR SELECT SALE_ID, REGION FROM SALES_T148B
                        WHERE SALE_ID <= 3 ORDER BY SALE_ID;
    THE_ID   NUMBER;
    THE_REG  VARCHAR;
    GUARD    NUMBER DEFAULT 0;
BEGIN
    FOR R IN C1 DO
        THE_ID  := R.SALE_ID;
        THE_REG := R.REGION;
        INSERT INTO TRACE_T148B (STEP, NOTE)
            VALUES (:THE_ID, 'walked ' || :THE_REG);
        GUARD := :GUARD + 1;
        IF (:GUARD >= 10) THEN BREAK; END IF;
    END FOR;
    RETURN 'wrote ' || :GUARD || ' rows';
END;
$$;
Result1 row · 1 column
status
Function CURDML_T148B successfully created.
Call
CALL CURDML_T148B();
Result1 row · 1 column
CURDML_T148B
wrote 3 rows
Query
SELECT STEP, NOTE FROM TRACE_T148B ORDER BY STEP;
Result3 rows · 2 columns
STEPNOTE
1walked north
2walked south
3walked east

One row per pass, with the region the cursor walked written into each one. That is the form that works.

There is a second way as well: skip the row object altogether and FETCH straight into variables, which are then ordinary variables with a colon in front of them.

Create
CREATE OR REPLACE PROCEDURE CURDMLFETCH_T148B()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
    C1       CURSOR FOR SELECT SALE_ID, REGION FROM SALES_T148B
                        WHERE SALE_ID = 4;
    THE_ID   NUMBER;
    THE_REG  VARCHAR;
BEGIN
    OPEN C1;
    FETCH C1 INTO THE_ID, THE_REG;
    INSERT INTO TRACE_T148B (STEP, NOTE)
        VALUES (:THE_ID, 'fetched ' || :THE_REG);
    CLOSE C1;
    RETURN 'wrote the fetched row';
END;
$$;
Result1 row · 1 column
status
Function CURDMLFETCH_T148B successfully created.
Call
CALL CURDMLFETCH_T148B();
Result1 row · 1 column
CURDMLFETCH_T148B
wrote the fetched row
Query
SELECT STEP, NOTE FROM TRACE_T148B ORDER BY STEP;
Result4 rows · 2 columns
STEPNOTE
1walked north
2walked south
3walked east
4fetched west

The three rows the walking version wrote, and the one the fetching version added. Both forms work, and neither of them uses a row object inside the INSERT.

Key points

  • A FOR loop over a cursor needs no OPEN. The loop opens it, and writing OPEN yourself changes nothing.
  • The row object uses the alias from the cursor's query, not the base column name.
  • Asking the row for a column the query never selected is created happily and fails at call time with 100183.
  • FETCH takes one row at a time, and six rows take seven fetches. The last fetch leaves the variable null, which is the exit condition rather than an error.
  • FETCH with no OPEN and CLOSE with no OPEN both give 092201, the cursor is not open.
  • A question mark in the cursor's query is bound with OPEN ... USING. A colon variable in a cursor query is 002049.
  • OPEN is the moment that fixes what the cursor will see. A row inserted after it was invisible to it.
  • An empty cursor runs its loop body no times at all, and a missing table is found at call time with the owner's rights.
  • A RESULTSET can be walked by a FOR loop with no cursor at all, and a cursor can be declared for a RESULTSET.
  • TABLE(RS) inside a block is a syntax error, and RESULT_SCAN wants a query id rather than a RESULTSET.
  • To count a RESULTSET, walk it and count the passes, or hand the rows back and let the caller count them.
  • A cursor and a RESULTSET each walk a query exactly once, and a second loop over either one gets nothing.
  • Assigning the query again rewinds a RESULTSET. CLOSE then OPEN rewinds a cursor.
  • A row object's field does not resolve inside an INSERT. Copy it into a variable first, or FETCH into variables instead.
Next in this series

In the next post we handle things going wrong on purpose: exceptions and RAISE. Declaring an exception, catching one, what the handler can see, and what the rows a block already wrote are doing while all that happens.

Every query and every result grid on this page was captured from a live Snowflake account (version 10.35.101) running the demo script for this episode. The rewinds, the two counting methods and the working form of the insert were captured in a second pass, on their own tables, which is why those procedure names end in B. Every loop on the page carries a guard, which is in the bodies above. Every count in the text is read off one of the grids on this page. Nothing is timed and no performance claims are made anywhere in this series. Behaviour follows the Snowflake Scripting cursors documentation.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.