简体   繁体   English

雪花(存储过程):将表中的 json object 展平成几列

[英]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.我有一张雪花表,其中有一列包含 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.问题是我想对具有不同 json 模式的不同表使用相同的存储过程。 In the example below the json consists of two key/value pairs.在下面的示例中,json 由两个键/值对组成。 For another table there could be 5 key/value pairs which need to flatten.对于另一个表,可能有 5 个键/值对需要展平。

Is it possible to do this with one stored procedure?是否可以使用一个存储过程来做到这一点? If yes, how can I do that?如果是,我该怎么做?

Original table原表

Animal动物 Name姓名 Details (json blob)详细信息(json blob)
Lion狮子 Georg乔治 lion key1: value1, lion key2: value2狮子键1:值1,狮子键2:值2
Lion狮子 Patrick帕特里克 lion key1: value1, lion key2: value2狮子键1:值1,狮子键2:值2

New table: Lion table新桌:狮子桌

Name姓名 lion key1狮子钥匙1 lion key2狮子钥匙2
Georg乔治 value1价值1 value2价值2
Patrick帕特里克 value1价值1 value2价值2
Paul保罗 value1价值1 value2价值2

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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