Snowflake Advanced Stored Procedures
Advanced stored procedures in Snowflake enable complex business logic implementation with error handling, dynamic SQL, transactions, and optimized performance patterns.
What are Advanced Stored Procedures?
- Implement complex business logic in SQL, JavaScript, or Python
- Use cursors, loops, and conditional branching
- Control transactions with COMMIT/ROLLBACK and savepoints
Architecture Overview
The advanced stored procedure architecture includes three layers:
- Input Layer â Parameters, table functions, caller context, session variables, bind variables
- Stored Procedure Engine
| Component | Elements |
|---|---|
| Variables | DECLARE, LET, SET, Cursors, Arrays |
| Control | IF/ELSE, CASE, FOR/WHILE, LOOP, RETURN |
| Error | BEGIN, EXCEPTION, WHEN, SQLCODE, SQLERRM |
- SQL Execution â Static SQL, dynamic SQL, EXECUTE IMMEDIATE, result sets, transactions
Advanced Patterns
- Cursor Pattern â Row-by-row processing
- Dynamic SQL â Schema-agnostic execution
- Transaction Control â BEGIN TRANSACTION, COMMIT/ROLLBACK, savepoints
- Performance â Batch processing, bulk operations, result caching, parallel execution
Stored Procedure Patterns
Basic Procedure with Error Handling
CREATE OR REPLACE PROCEDURE process_data(table_name VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
EXECUTE AS CALLER
AS
DECLARE
row_count INTEGER;
error_msg VARCHAR;
BEGIN
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || table_name INTO row_count;
EXECUTE IMMEDIATE '
INSERT INTO target_table
SELECT * FROM ' || table_name || ' WHERE processed = FALSE
';
RETURN 'Successfully processed ' || :row_count || ' rows';
EXCEPTION
WHEN OTHER THEN
error_msg := 'Error processing ' || table_name || ': ' || SQLERRM;
INSERT INTO error_log (procedure_name, error_message, timestamp)
VALUES ('process_data', :error_msg, CURRENT_TIMESTAMP());
RAISE;
END;
Cursor-Based Processing
CREATE OR REPLACE PROCEDURE cursor_processing()
RETURNS VARCHAR
LANGUAGE SQL
AS
DECLARE
cursor1 CURSOR FOR SELECT id, name FROM source_table;
id INTEGER;
name VARCHAR;
BEGIN
OPEN cursor1;
FOR record IN cursor1 DO
id := record.id;
name := record.name;
INSERT INTO target_table (id, name, processed_at)
VALUES (:id, :name, CURRENT_TIMESTAMP());
END FOR;
CLOSE cursor1;
RETURN 'Cursor processing complete';
END;
Dynamic SQL Pattern
CREATE OR REPLACE PROCEDURE dynamic_processing(schema_name VARCHAR, table_name VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
DECLARE
sql_stmt VARCHAR;
row_count INTEGER;
BEGIN
sql_stmt := 'SELECT COUNT(*) FROM ' || schema_name || '.' || table_name;
EXECUTE IMMEDIATE :sql_stmt INTO row_count;
IF (:row_count > 1000) THEN
sql_stmt := 'INSERT INTO target SELECT * FROM ' || schema_name || '.' || table_name || ' LIMIT 1000';
ELSE
sql_stmt := 'INSERT INTO target SELECT * FROM ' || schema_name || '.' || table_name;
END IF;
EXECUTE IMMEDIATE :sql_stmt;
RETURN 'Processed ' || :row_count || ' rows from ' || table_name;
END;
Transaction Control
CREATE OR REPLACE PROCEDURE transaction_example()
RETURNS VARCHAR
LANGUAGE SQL
AS
BEGIN
BEGIN TRANSACTION;
INSERT INTO table_a (id, data) VALUES (1, 'test');
SAVEPOINT sp1;
INSERT INTO table_b (id, data) VALUES (1, 'test');
COMMIT;
RETURN 'Transaction completed successfully';
EXCEPTION
WHEN OTHER THEN
ROLLBACK TO SAVEPOINT sp1;
INSERT INTO error_log (error_message) VALUES (SQLERRM);
RETURN 'Transaction failed: ' || SQLERRM;
END;
Performance Optimization
CREATE OR REPLACE PROCEDURE batch_processing(batch_size INTEGER)
RETURNS VARCHAR
LANGUAGE SQL
AS
DECLARE
total_rows INTEGER;
processed INTEGER := 0;
BEGIN
SELECT COUNT(*) INTO total_rows FROM source WHERE processed = FALSE;
WHILE processed < total_rows DO
INSERT INTO target
SELECT * FROM source
WHERE processed = FALSE
LIMIT :batch_size;
UPDATE source SET processed = TRUE
WHERE id IN (SELECT id FROM target ORDER BY id DESC LIMIT :batch_size);
processed := processed + :batch_size;
END WHILE;
RETURN 'Processed ' || :processed || ' rows in batches of ' || :batch_size;
END;
Procedure Comparison
| Feature | SQL | JavaScript | Python |
|---|---|---|---|
| Error Handling | TRY/CATCH | try/catch | try/except |
| Dynamic SQL | EXECUTE IMMEDIATE | snowflake.execute | cursor.execute |
| External Calls | Limited | HTTP support | Full libraries |
| Performance | Good | Better for logic | Best for ML |
| Complexity | Simple | Medium | High |
See Also
- Stored Procedures â Fundamentals of creating and calling stored procedures
- Snowpark Python â Build data pipelines and ML models with Python
- UDF Advanced â Create custom scalar and table functions
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions