1

I have one table in snowflake with a column which contains a json blob. I want to flatten that column with a stored procedure. The issue is that I'd like to use the same stored procedure for different tables with different json schemas. In the example below the json consists of two key/value pairs. For another table there could be 5 key/value pairs which need to flatten.

Is it possible to do this with one stored procedure? If yes, how can I do that?

Original table

Animal Name Details (json blob)
Lion Georg lion key1: value1, lion key2: value2
Lion Patrick lion key1: value1, lion key2: value2

New table: Lion table

Name lion key1 lion key2
Georg value1 value2
Patrick value1 value2
Paul value1 value2
1

1 Answer 1

0

I don't think it's feasible but here is a sample procedure:

CREATE OR REPLACE PROCEDURE generate_dynamic_table()
RETURNS VARCHAR
LANGUAGE SQL
AS
DECLARE
   c1 CURSOR FOR select DISTINCT KEY from mytable, lateral flatten( details );
   SQLstatement VARCHAR := 'CREATE TABLE targettable ( Name, ';
   SELstmt VARCHAR := 'AS SELECT Name, '; 
BEGIN
   FOR c IN c1 DO
      SQLstatement := SQLstatement || '"' || c.KEY || '", '; 
      SELstmt := SELstmt || 'details:"' || c.KEY || '", ';
   END FOR;
   SQLstatement := LEFT( SQLstatement, LEN(SQLstatement) - 2 ) || ') ';
   SELstmt := LEFT( SELstmt, LEN(SELstmt) - 2 ) || '';
   SQLstatement := SQLstatement || SELstmt || ' FROM mytable';
   EXECUTE IMMEDIATE SQLstatement;
   RETURN 'OK';
END;

call generate_dynamic_table();

After running the procedure:

select * from targettable;

+---------+-----------+-----------+
|  NAME   | lion key1 | lion key2 |
+---------+-----------+-----------+
| Georg   | "value1"  | "value2"  |
| Patrick | "value1"  | "value2"  |
+---------+-----------+-----------+
Sign up to request clarification or add additional context in comments.

2 Comments

What do you mean by it's not feasible? What's the limitation of your proposed solution?
@siva I meant generating auto tables from a table. There is no limitation of SP., but if the table is not simple as you shared, or JSON is more complex, the SP would be very complex and open to errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.