简体   繁体   中英

Snowflake (stored procedure): flatten json object in table into several columns

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

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"  |
+---------+-----------+-----------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM