Creating procedures in snowflake allows you to package up lots of code into one function to be run together.

Creating a procedure

To create a procedure in Snowflake, you start off by declaring the name, the data type that the function returns and the coding language.

SQL
CREATE PROCEDURE MY_PROC_NAME()
RETURNS DATA_TYPE
LANGUAGE CODE_LANGUAGE
AS

Before you insert your code the procedure requires two dollar signs to indicate the start of the procedure (and again for the end with the additional semi-colon).

Plain text
$$
$$;

Then BEGIN and END; are also required to command what to do. You can then insert your code for your procedure between these. It is important to note that you can have more than one statement inside a procedure.

Plain text
BEGIN
  //SQL statement1;
  //SQL statement2;
END;

So the final procedure will look like the following:

SQL
CREATE PROCEDURE MY_PROC_NAME()
RETURNS DATA_TYPE
LANGUAGE CODE_LANGUAGE
AS
$$
BEGIN
  //SQL statement1;
  //SQL statement2;
END;
$$;

Transactions

To catch errors and prevent your output from being half complete you may want to add transactions. Transactions allow you to only commit the changes if the whole statement is successful, and if not will roll back the changes. You can have multiple transactions inside a procedure but you cannot nest transactions within each other. You can wrap one or multiple statements within a transaction.

To create a transaction, you need to tell Snowflake to BEGIN TRANSACTION;.

Then after the statement(s) wrapped inside, COMMIT which means that if the statement(s) are successful then make the changes. It is helpful to include an output here to say that the changes have been made using the RETURN command.

Following this, we will tell Snowflake what to do if the statement(s) are unsuccessful. To declare this we write

Plain text
EXCEPTION
  WHEN OTHER THEN
    ROLLBACK;
    RAISE;

Rollback reverts the changes to the previous version and raise ensures the error is shown in the results view.

The overall procedure might now look like the following:

SQL
CREATE PROCEDURE MY_PROC_NAME()
RETURNS DATA_TYPE
LANGUAGE CODE_LANGUAGE
AS
$$
BEGIN
  BEGIN TRANSACTION;
    //SQL statement1;
    //SQL statement2;
    COMMIT;
    RETURN ‘Changes made successfully’;
  EXCEPTION
    WHEN OTHER THEN
      ROLLBACK;
      RAISE;
END;
$$;

 Alternatively, it could look like the following:

SQL
CREATE PROCEDURE MY_PROC_NAME()
RETURNS DATA_TYPE
LANGUAGE CODE_LANGUAGE
AS
$$
BEGIN
  //SQL statement1;
  BEGIN TRANSACTION;
    //SQL statement2;
    COMMIT;
    RETURN ‘Changes made successfully’;
  EXCEPTION
    WHEN OTHER THEN
      ROLLBACK;
      RAISE;
END;
$$;

 You have now created your procedures! You can then schedule the procedures to run using tasks instead of running these manually.