snowflake - parse_json

2sbarzqh  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(97)

我有一个SQL查询,我想在where子句中过滤下一个逻辑之后的不同行,例如:
where table1.field1 in(function1(:json_name))
所以函数function1定义为:

CREATE FUNCTION IF NOT EXISTS db.schema.function1(json_name VARCHAR) 
RETURNS TABLE(json_col VARCHAR) 
AS $$ 
DECLARE 
    exception1 EXCEPTION (-20001, 'Error'); 
BEGIN
    select parse_json(:json_name as src) src, lateral flatten(input => src) ) 
    where value is not null; 
END; $$;

字符串
但我得到的错误,

Syntax error:L compilation error: (line 3)
syntax error line 3 at position 4 unexpected 'exception1'.
syntax error line 3 at position 29 unexpected '-'.
syntax error line 3 at position 35 unexpected ','. (line 3)


有什么想法

hvvq6cgz

hvvq6cgz1#

对于snowflake,我建议使用javascript,如下所示:

CREATE OR REPLACE FUNCTION db.schema.function1(json_name STRING)
RETURNS TABLE(json_col STRING)
LANGUAGE JAVASCRIPT
AS
$$
    var parsed = JSON.parse(json_name);
    var flattened = [];
    
    for (var key in parsed) {
        if (parsed.hasOwnProperty(key) && parsed[key] !== null) {
            flattened.push([parsed[key]]);
        }
    }
    
    return flattened;
$$;

字符串
把它叫做:

SELECT *
FROM table1 t
WHERE t.field1 IN (SELECT * FROM TABLE(db.schema.function1(:json_name)));


您需要更正“db.schema”引用,并且您可能希望包含“try/catch”用于错误处理,例如:

CREATE OR REPLACE PROCEDURE db.schema.function1(json_name STRING)
RETURNS STRING
LANGUAGE JAVASCRIPT
AS
$$
    var flattened = [];
    try {
        var parsed = JSON.parse(json_name);
        for (var key in parsed) {
            if (parsed.hasOwnProperty(key) && parsed[key] !== null) {
                flattened.push(parsed[key]);
            }
        }
    } catch (err) {
        // handle error here
        return "Error: " + err.message;
    }
    return flattened.join(',');
$$;

相关问题