如何在Snowflake存储过程中提取JSON值

fumotvh3  于 2023-10-21  发布在  其他
关注(0)|答案(1)|浏览(148)

在一个snowflake sql存储过程中,我有一个JSON对象设置为一个名为json_object的变量:

{"level":1,"object":"OBJECT1","object_schema":"SCHEMA1","object_type":"TABLE"}, 
{"level":2,"object":"OBJECT2","object_schema":"SCHEMA2","object_type":"TABLE"}, 
{"level":3,"object":"OBJECT3","object_schema":"SCHEMA3","object_type":"TABLE"}

在过程中,我想提取每个键值(level,object,object_schema,object_type)并将这些值放入变量中。我不知道该不该把它放进table里。我试过

extract_json :=  'SELECT level[0] from '||: json_object ||';';

但我确信这绝对是错误的,那么在 snowflake 存储过程中提取JSON键及其值的正确方法是什么呢?谢谢你,谢谢

wtzytmuj

wtzytmuj1#

你必须使用动态SQL,下面是你的起点,如果你的输入没有被 Package 在方括号中,然后扁平化,那么你将为每个JSON记录获得一行。然后简单地运行循环。

begin
let jsonstring varchar := '[{"level":1,"object":"OBJECT1","object_schema":"SCHEMA1","object_type":"TABLE"}, 
{"level":2,"object":"OBJECT2","object_schema":"SCHEMA2","object_type":"TABLE"}, 
{"level":3,"object":"OBJECT3","object_schema":"SCHEMA3","object_type":"TABLE"}]';

let sql varchar := 'select value:"level"::varchar level
    ,value:"object"::varchar object
    ,value:"object_schema"::varchar object_schema
    ,value:"object_type"::varchar object_type
    from (
        select parse_json(''' || jsonstring || ''') val
    ) n
    ,lateral flatten(n.val);';
    let res resultset := (execute immediate :sql);
    let c1 CURSOR FOR res;

    let lev varchar;
    let ob varchar;
    let ob_sc varchar;
    let ob_tp varchar;
    for i in c1
    do 
     lev:= i.level;
     ob:= i.object;
     ob_sc:= i.object_schema;
     ob_tp:= i.object_type;

    // Do what you want to do with values
    end for;
    
    return table(res);

end
;

相关问题