In this post we are going to cover anonymous procedures in Snowflake.
An anonymous procedure is a procedure you never create. You declare it inside a WITH clause, you call it in the same statement, and when that statement is over it is gone. There is nothing in the catalog and nothing to drop.
It exists for exactly one statement. But what it does while it is alive is permanent, and that pairing is the whole post.
We will start with the smallest one there is and build it up step by step. Every query below was run on a real Snowflake account, and every result and every error you see is what it gave back.
Episode 151 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- Let's start with the smallest anonymous procedure
- Now let's wrap the body in dollar signs
- Two things that are not optional
- So where is the procedure now?
- Two more ways to write that wrong
- So what can go in the body?
- Now let's return rows instead of a value
- Can a CTE and a procedure share one WITH clause?
- And two procedures in one WITH clause?
- Now the part this post is built around
- Whose privileges does it run with?
- Can the body be another language?
- One last thing: the arguments are checked the usual way
- And the clean-up, which is almost nothing
Let's create some sample data
First let's see where the session is pointing.
SELECT CURRENT_DATABASE() AS THE_DATABASE,
CURRENT_SCHEMA() AS THE_SCHEMA,
CURRENT_VERSION() AS THE_VERSION;| THE_DATABASE | THE_SCHEMA | THE_VERSION |
|---|---|---|
| DEMO_DB | PUBLIC | 10.35.101 |
Now a small sales table, and five rows in it.
CREATE OR REPLACE TABLE SALES_T151 (
SALE_ID INT,
REGION VARCHAR(10),
AMOUNT NUMBER(10,2)
);| status |
|---|
| Table SALES_T151 successfully created. |
INSERT INTO SALES_T151 (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);| number of rows inserted |
|---|
| 5 |
And a count to confirm what is in there.
SELECT COUNT(*) AS HOW_MANY, SUM(AMOUNT) AS TOTAL_AMOUNT FROM SALES_T151;| HOW_MANY | TOTAL_AMOUNT |
|---|---|
| 5 | 780.75 |
Five rows and a total of 780.75. That is everything this post reads.
Let's start with the smallest anonymous procedure
Here is the whole thing. Read the first line, and notice what is not there.
WITH DOUBLE_T151 AS PROCEDURE (N NUMBER)
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
RETURN :N * 2;
END
CALL DOUBLE_T151(21);| DOUBLE_T151 |
|---|
| 42 |
Forty two, so it ran and it worked.
Now look at the shape of what we wrote. There is no CREATE anywhere in it. The word PROCEDURE comes after AS, inside a WITH clause, and the name in front of it is just a label.
And the CALL at the bottom is part of the same statement. That is why it can see a name that nothing else can.
WITH, then the name you want to useAS PROCEDURE, with the arguments after itRETURNS, thenLANGUAGE, thenAS- the body
- and then the statement that uses it, with no semicolon between them
Now let's wrap the body in dollar signs
Every procedure in this course so far has had its body between a pair of $$. Let's write the same one that way.
WITH DOLLARS_T151 AS PROCEDURE (N NUMBER)
RETURNS NUMBER
LANGUAGE SQL
AS
$$
BEGIN
RETURN :N * 2;
END;
$$
CALL DOLLARS_T151(21);| DOLLARS_T151 |
|---|
| 42 |
Also forty two. Both spellings are fine, so use whichever you find easier to read.
Two things that are not optional
First let's leave out the RETURNS clause.
WITH NORETURNS_T151 AS PROCEDURE ()
LANGUAGE SQL
AS
BEGIN
RETURN 1;
END
CALL NORETURNS_T151();092226 (42601): SQL compilation error: stored procedure definition is missing return type
092226, missing return type. So RETURNS is required even though nothing is being registered anywhere.
And second, a body that is not a block. Just a RETURN, with no BEGIN and no END.
WITH NOBLOCK_T151 AS PROCEDURE ()
RETURNS NUMBER
LANGUAGE SQL
AS
RETURN 1;
CALL NOBLOCK_T151();001003 (42000): SQL compilation error: syntax error line 5 at position 4 unexpected 'RETURN'.
001003. The body has to be a block, the same as it does in a procedure you create.
So where is the procedure now?
A moment ago that call gave us a number back. Let's ask the catalog about the name.
SHOW PROCEDURES LIKE 'DOUBLE\\_T151';| created_on | name | schema_name | is_builtin | is_aggregate | is_ansi | min_num_arguments | max_num_arguments | arguments | description | catalog_name | is_table_function | valid_for_clustering | is_secure | secrets | external_access_integrations |
|---|
Nothing at all. The grid is empty, so the name was never registered anywhere.
Let's ask a second way. Just call it again, on its own, as the next statement.
CALL DOUBLE_T151(21);002139 (02000): SQL compilation error: Unknown function DOUBLE_T151.
002139, unknown function. So the procedure existed for exactly one statement, and that statement is over.
And a third way, from the other end. Let's try to drop it.
DROP PROCEDURE IF EXISTS DEMO_DB.PUBLIC.DOUBLE_T151(NUMBER);| status |
|---|
| Drop statement executed successfully (DOUBLE_T151 already dropped). |
Already dropped. There was never anything there to drop.
Two more ways to write that wrong
Let's declare one name and then call a different one.
WITH MISMATCH_T151 AS PROCEDURE ()
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
RETURN 1;
END
CALL NOT_THAT_NAME_T151();002139 (02000): SQL compilation error: Unknown function NOT_THAT_NAME_T151.
Unknown function again. The call has to name the procedure we just declared, because that label is the only thing that knows it exists.
And now a WITH clause with nothing after it at all.
WITH LONELY_T151 AS PROCEDURE ()
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
RETURN 1;
END001003 (42000): SQL compilation error: syntax error line 13 at position 40 unexpected '<EOF>'.
Unexpected end of file. The statement is not finished, because a declaration on its own is not a statement.
The position in that message points further down than the statement above it. In the demo file this is the last statement, and an anonymous procedure has no terminator, so the comment block that follows it got read as part of the same statement. The code block above shows the statement without that comment. Nothing else about it was changed.
So what can go in the body?
Everything that can go in a procedure you create. Let's start with a DECLARE section and a SELECT ... INTO.
WITH DECLARED_T151 AS PROCEDURE ()
RETURNS VARCHAR
LANGUAGE SQL
AS
DECLARE
THE_LABEL VARCHAR DEFAULT 'it declared';
HOW_MANY NUMBER;
BEGIN
SELECT COUNT(*) INTO :HOW_MANY FROM SALES_T151;
RETURN :THE_LABEL || ' and counted ' || :HOW_MANY;
END
CALL DECLARED_T151();| DECLARED_T151 |
|---|
| it declared and counted 5 |
So the declare section works, and the body can read a table.
Now a loop.
WITH LOOPED_T151 AS PROCEDURE ()
RETURNS VARCHAR
LANGUAGE SQL
AS
DECLARE
OUT_TEXT VARCHAR DEFAULT '';
BEGIN
FOR I IN 1 TO 3 DO
OUT_TEXT := :OUT_TEXT || :I || ' ';
END FOR;
RETURN 'visited: ' || :OUT_TEXT;
END
CALL LOOPED_T151();| LOOPED_T151 |
|---|
| visited: 1 2 3 |
A FOR loop, behaving exactly the way it does anywhere else, inside something with no name.
And now an exception handler.
WITH HANDLED_T151 AS PROCEDURE ()
RETURNS VARCHAR
LANGUAGE SQL
AS
BEGIN
RAISE STATEMENT_ERROR;
RETURN 'never reached';
EXCEPTION
WHEN STATEMENT_ERROR THEN
RETURN 'the handler ran in an anonymous procedure';
END
CALL HANDLED_T151();| HANDLED_T151 |
|---|
| the handler ran in an anonymous procedure |
The handler ran. So everything from the last post applies here unchanged.
Now let's return rows instead of a value
Let's declare a RESULTSET, give it a query, and hand the rows back with RETURN TABLE.
WITH TABLED_T151 AS PROCEDURE (CUTOFF NUMBER)
RETURNS TABLE (SALE_ID INT, THE_AMOUNT NUMBER(10,2))
LANGUAGE SQL
AS
DECLARE
RS RESULTSET;
BEGIN
RS := (SELECT SALE_ID, AMOUNT FROM SALES_T151 WHERE AMOUNT > :CUTOFF
ORDER BY SALE_ID);
RETURN TABLE(RS);
END
CALL TABLED_T151(80);| SALE_ID | THE_AMOUNT |
|---|---|
| 1 | 100.00 |
| 2 | 250.50 |
| 4 | 310.00 |
Three rows, the ones over the cutoff we passed in.
Now a question worth asking. The procedure is gone the moment that statement ended. Can the next statement still get at those rows?
SELECT SALE_ID, THE_AMOUNT FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
ORDER BY SALE_ID;| SALE_ID | THE_AMOUNT |
|---|---|
| 1 | 100.00 |
| 2 | 250.50 |
| 4 | 310.00 |
The same three rows, and there is no procedure named anywhere in that query. So the rows outlive the procedure even though the name does not.
Hold on to that, because it is where this post is going.
Can a CTE and a procedure share one WITH clause?
A WITH clause already holds CTEs, so this is a fair question. Let's put a CTE first and then a procedure that counts its rows.
WITH BIG_ONES AS (
SELECT SALE_ID, AMOUNT FROM SALES_T151 WHERE AMOUNT > 80
),
COUNTER_T151 AS PROCEDURE ()
RETURNS NUMBER
LANGUAGE SQL
AS
DECLARE
HOW_MANY NUMBER;
BEGIN
SELECT COUNT(*) INTO :HOW_MANY FROM BIG_ONES;
RETURN :HOW_MANY;
END
CALL COUNTER_T151();002003 (42S02): Uncaught exception of type 'STATEMENT_ERROR' on line 4 at position 4 : SQL compilation error: Object 'BIG_ONES' does not exist or not authorized. Your primary role ACCOUNTADMIN or one of your secondary roles must have at least one privilege granted on TABLE BIG_ONES.
002003, the object does not exist. So the procedure body cannot see its neighbour in the same WITH clause.
And that is not the CTE being broken. On its own it behaves exactly the way Level 4 taught it.
WITH BIG_ONES AS (
SELECT SALE_ID, AMOUNT FROM SALES_T151 WHERE AMOUNT > 80
)
SELECT COUNT(*) AS HOW_MANY FROM BIG_ONES;| HOW_MANY |
|---|
| 3 |
Now the same two the other way round. Read the body carefully, because it counts the table and not the CTE.
WITH COUNTER2_T151 AS PROCEDURE ()
RETURNS NUMBER
LANGUAGE SQL
AS
DECLARE
HOW_MANY NUMBER;
BEGIN
SELECT COUNT(*) INTO :HOW_MANY FROM SALES_T151;
RETURN :HOW_MANY;
END,
BIG_ONES AS (
SELECT SALE_ID FROM SALES_T151 WHERE AMOUNT > 80
)
CALL COUNTER2_T151();| COUNTER2_T151 |
|---|
| 5 |
Created and called with no complaint. So the two can share one WITH clause perfectly happily.
What the body cannot do is see the CTE. That is about scope, not about which one you write first, and this run did not test the order on its own.
And the statement after it does not have to be a call
WITH UNUSED_T151 AS PROCEDURE ()
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
RETURN 1;
END
SELECT COUNT(*) AS HOW_MANY FROM SALES_T151;| HOW_MANY |
|---|
| 5 |
The procedure was declared and never called, and the SELECT ran as if the WITH clause were not there.
And two procedures in one WITH clause?
Let's declare two, separated by a comma, and call the second one.
WITH HALF_T151 AS PROCEDURE (N NUMBER)
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
RETURN :N / 2;
END,
QUARTER_T151 AS PROCEDURE (N NUMBER)
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
RETURN :N / 4;
END
CALL QUARTER_T151(100);| QUARTER_T151 |
|---|
| 25.000000 |
A quarter of a hundred. So both of them were declared, and the one we named is the one that ran. The trailing zeros are what dividing a NUMBER hands back.
But can one of them call the other? Let's write one that calls its neighbour and reads the answer back.
WITH INNER_T151 AS PROCEDURE (N NUMBER)
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
RETURN :N * 2;
END,
OUTER_T151 AS PROCEDURE (N NUMBER)
RETURNS NUMBER
LANGUAGE SQL
AS
DECLARE
THE_ANSWER NUMBER;
BEGIN
CALL INNER_T151(:N);
SELECT INNER_T151 INTO :THE_ANSWER FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
RETURN :THE_ANSWER + 1;
END
CALL OUTER_T151(10)002139 (02000): Uncaught exception of type 'STATEMENT_ERROR' on line 4 at position 4 : SQL compilation error: Unknown function INNER_T151.
No. Unknown function again. They cannot see each other any more than they can see a CTE.
Now the part this post is built around
Let's write an anonymous procedure that inserts a row.
WITH WRITER_T151 AS PROCEDURE ()
RETURNS VARCHAR
LANGUAGE SQL
AS
BEGIN
INSERT INTO SALES_T151 (SALE_ID, REGION, AMOUNT)
VALUES (90, 'anon', 7.00);
RETURN 'wrote a row';
END
CALL WRITER_T151();| WRITER_T151 |
|---|
| wrote a row |
It wrote a row. And by the time that message came back the procedure was already gone.
So here is the question. Is the row gone with it? Let's go and look for it.
SELECT SALE_ID, REGION, AMOUNT FROM SALES_T151 WHERE SALE_ID = 90;| SALE_ID | REGION | AMOUNT |
|---|---|---|
| 90 | anon | 7.00 |
There it is, still in the table.
The definition lasted one statement. What it did is permanent. There is nothing in the catalog to tell you that row was ever written by a procedure, because there was never a procedure to tell you about.
Which is the whole reason this shape exists. For a one-off job you do not want to leave a procedure behind, and this leaves none.
Whose privileges does it run with?
Let's ask it directly, with EXECUTE AS CALLER written out.
WITH ASCALLER_T151 AS PROCEDURE ()
RETURNS VARCHAR
LANGUAGE SQL
EXECUTE AS CALLER
AS
BEGIN
RETURN 'running as ' || CURRENT_ROLE();
END
CALL ASCALLER_T151();| ASCALLER_T151 |
|---|
| running as ACCOUNTADMIN |
That is the role the session was using, so it ran as the caller.
Now let's try to say EXECUTE AS OWNER instead.
WITH ASOWNER_T151 AS PROCEDURE ()
RETURNS VARCHAR
LANGUAGE SQL
EXECUTE AS OWNER
AS
BEGIN
RETURN 'running as ' || CURRENT_ROLE();
END
CALL ASOWNER_T151()090274 (42601): Anonymous procedures are callers rights only. Explicitly setting this property is not needed.
090274, and that message is better than any explanation I could write. There is no owner, because nothing was ever created.
Can the body be another language?
The body has been SQL so far. Let's try JavaScript in the same shape.
WITH JSPROC_T151 AS PROCEDURE (N FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
return N * 2;
$$
CALL JSPROC_T151(21);| JSPROC_T151 |
|---|
| 42.0 |
Forty two, as a float. So the form takes a JavaScript body with no trouble at all.
Now Python, in the same shape.
WITH PYPROC_T151 AS PROCEDURE (N FLOAT)
RETURNS FLOAT
LANGUAGE PYTHON
RUNTIME_VERSION = '3.11'
HANDLER = 'f'
AS
$$
def f(n):
return n * 2
$$
CALL PYPROC_T151(21)100357 (P0000): Python Interpreter Error: ModuleNotFoundError: No module named 'snowflake.snowpark' in function PYPROC_T151 with handler f
A module-not-found error. Now read where that error came from. It says Python interpreter error and it names our handler, so the statement was accepted and the handler actually ran.
What it tripped on is a package a Python procedure needs, and the declaration above does not ask for one. That is an omission in what we wrote, not a limit of the form.
So this grid tells us Python gets as far as the interpreter, and nothing beyond that. We are not going to claim more than it shows.
One last thing: the arguments are checked the usual way
Let's declare one that takes a single argument and call it with two.
WITH ARITY_T151 AS PROCEDURE (N NUMBER)
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
RETURN :N;
END
CALL ARITY_T151(1, 2);000939 (22023): SQL compilation error: error line 0 at position -1 too many arguments for function [ARITY_T151(1, 2)] expected 1, got 2
Too many arguments, and it says what it expected and what it got. Nothing special about anonymous procedures here. The arity is checked the same way it is for any function.
And the clean-up, which is almost nothing
There is one table to drop, and that is it.
DROP TABLE IF EXISTS DEMO_DB.PUBLIC.SALES_T151;| status |
|---|
| SALES_T151 successfully dropped. |
Now the checks afterwards.
SELECT CURRENT_DATABASE() AS THE_DATABASE,
CURRENT_SCHEMA() AS THE_SCHEMA,
CURRENT_TRANSACTION() AS ANY_OPEN_TRANSACTION;| THE_DATABASE | THE_SCHEMA | ANY_OPEN_TRANSACTION |
|---|---|---|
| DEMO_DB | PUBLIC | NULL |
SHOW PROCEDURES LIKE '%\\_T151';| created_on | name | schema_name | is_builtin | is_aggregate | is_ansi | min_num_arguments | max_num_arguments | arguments | description | catalog_name | is_table_function | valid_for_clustering | is_secure | secrets | external_access_integrations |
|---|
SELECT COUNT(*) AS PROBE_TABLES_LEFT
FROM DEMO_DB.INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'PUBLIC' AND ENDSWITH(TABLE_NAME, '_T151');| PROBE_TABLES_LEFT |
|---|
| 0 |
Same database and schema, nothing open, an empty grid where the procedures would be, and no tables left. The empty grid is the point of the whole post.
Key points
- An anonymous procedure is
WITH, a name,AS PROCEDURE, the body, and then the statement that uses it. All one statement, and noCREATEanywhere. - The body can be wrapped in
$$or written bare. Both work. RETURNSis not optional, and the body has to be a block. Those are092226and001003.- Nothing goes in the catalog.
SHOW PROCEDURESfinds nothing, calling the name on its own line is002139, and aDROPreports it was already dropped. - The call has to name the procedure you just declared, and a
WITHclause with nothing after it is not a statement. - Inside the body you get the whole language: a
DECLAREsection, a loop, an exception handler, and aRESULTSEThanded back withRETURN TABLE. - The next statement can read those rows back with
RESULT_SCAN. The rows outlive the name. - A CTE and a procedure can share one
WITHclause, but the body cannot see the CTE. - Two procedures can share one
WITHclause, and neither can call the other. - A row an anonymous procedure wrote is still there after the procedure has gone. The definition lasts one statement. What it did is permanent.
- It is always the caller's rights.
EXECUTE AS OWNERis090274, because there is no owner. - A JavaScript body works in the same form. The Python one here reached the interpreter and stopped on a package it was never given.
- Too many arguments is
000939, checked the same way as for any function.
In the next post we stop running things and start reading plans: EXPLAIN. What the steps mean, what the partition columns are telling you, and a count that proves EXPLAIN did not run the query.
Every query, every result grid and every error pane on this page was captured from a live Snowflake account (version 10.35.101) running the demo script for this episode. Four of the statements above are shown without the demo file's own banner comment, which the capture swept up because an anonymous procedure has no terminator; nothing else about any statement was changed, and the error panes are printed exactly as they came back. Every count in the text is read off one of the grids on this page. No account identifier, user name or query id appears anywhere on this page. Nothing is timed and no performance claims are made anywhere in this series. Behaviour follows the Snowflake anonymous procedures documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.