Clob的DB2长度(JSON)

lhcgjxsq  于 2022-12-04  发布在  DB2
关注(0)|答案(1)|浏览(224)

我在存储过程中生成一个json,如下所示

Declare res CLOB(5M);
Set res =  (values (json_array(select json_object…

Json看起来像

[{pk: 1, name1: xyz, name: 2}, {pk: 2, name1: cvc, name2: vcc}]

最后我需要的信息是什么是json的长度,意味着多少条目,它有,从根开始.
我需要这样的东西,

Declare counter SMALLINT;
Set Counter = xyz —should be 2

那么我怎么才能从res中找出,有两行呢?

omvjsjqw

omvjsjqw1#

--# SET TERMINATOR @

-- Create a generic function to deal with JSON arrays
CREATE OR REPLACE FUNCTION UNNEST_JSON (P_DOC CLOB(1M), P_PATH VARCHAR(128))
RETURNS TABLE
(
  INDEX INT
, ITEM  CLOB (1M)
)
DETERMINISTIC
NO EXTERNAL ACTION
BEGIN 
  DECLARE L_IDX INT DEFAULT 0;
  
  L1: 
  WHILE TRUE DO
    IF NOT JSON_EXISTS (P_DOC, P_PATH || '[' || L_IDX || ']') THEN LEAVE L1; END IF; 
    PIPE (L_IDX, JSON_QUERY (P_DOC, P_PATH || '[' || L_IDX || ']'));
    SET L_IDX = L_IDX + 1;
  END WHILE L1;
  
  RETURN;  
END
@

SELECT COUNT (1) AS ELEM_NUM
FROM TABLE (UNNEST_JSON (
  -- You give your unnamed array some name you will refer in the 2-nd arg
  JSON_OBJECT
  (
    KEY 'items'
    VALUE    
    JSON_ARRAY
    (
      JSON_OBJECT (KEY 'pk' VALUE 1, KEY 'name1' VALUE 'xyz', KEY 'name'  VALUE 2) FORMAT JSON
    , JSON_OBJECT (KEY 'pk' VALUE 2, KEY 'name1' VALUE 'cvc', KEY 'name2' VALUE 'vcc') FORMAT JSON
    )
    FORMAT JSON
  )  
  , '$.items'
))
@

| 元素_编号|
| - -|
| 2个|

相关问题