Search code examples
db2-luw

DB2 LUW-Json_Table function Syntax errors


I am trying to Insert array of Json data into a temporary table in DB2. I came to know that I can achieve this using Json_Table function. I found 2 links for this function with different syntax.

Can somebody help understand the difference between them?

  1. https://www.ibm.com/support/producthub/db2/docs/content/SSEPGG_11.5.0/com.ibm.db2.luw.sql.ref.doc/doc/r0070414.html?pos=2

  2. https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.5.0/com.ibm.swg.im.dbclient.json.doc/doc/r0070289.html

As per my use-case i find link 1 is suitable, so i tried that example in DB2 LUW V11.1/V11.5 Environment I am getting Syntax errors saying JSON_Table is Invalid. Is the syntax in Link 1 not supported in DB2 LUW V11.1/V11.5? Am I missing anything here?

I just took sample code as it is from Link 1 (https://www.ibm.com/support/producthub/db2/docs/content/SSEPGG_11.5.0/com.ibm.db2.luw.sql.ref.doc/doc/r0070414.html?pos=2) as shown below

SELECT U."id", U."first name", U."last name", U."phone number"
FROM EMPLOYEE_TABLE E
JSON_TABLE(E.jsondoc, 'strict $'
           COLUMNS( "id" INTEGER,
                    "firstname"  VARCHAR(20),
                    "lastname"   VARCHAR(20),
                    "phoneno"    VARCHAR(20))
                    ERROR ON ERROR) AS U

I am getting Marker errors like "Multiple markers at this line

  • DB2 for Linux, UNIX, and Windows: "<table_expr>" was expected to form a complete scope.
  • DB2 for Linux, UNIX, and Windows: "U."id", U."first name", U."last name", U."phone number" FROM JSON_EMP E JSON_TABLE(E.EMP_DATA, 'strict $' COLUMNS( "id..."

When i tried to execute the above query I am getting Error as "‪An‬‎ ‪unexpected‬‎ ‪token‬‎ ‪‬‎"‪E"‬‎ ‪was‬‎ ‪found‬‎ ‪following‬‎ ‪‬‎"‪er"‬‎ ‪ ‬‎ ‪ FROM‬‎ ‪JSON_EMP‬‎"‪. Expected tokens may include: "EXCEPT‬‎"‪.. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.19.56"

I tried to prefix JSON_TABLE with schema sysibm, but still no luck. I got same errors.


Solution

  • There is a number of errors in this example from documentation:
    -- no comma before JSON_TABLE
    -- contradictions in column names between COLUMN clause and SELECT list

    Below is a working example:

    /*
    WITH EMPLOYEE_TABLE (jsondoc) AS 
    (
    VALUES 
    '
    {
      "id" : 901,
      "firstname" : "John",
      "lastname"  : "Doe",
      "phoneno"   : "555-3762"
    }
    '
    )
    */
    SELECT U."id", U."firstname", U."lastname", U."phoneno"
    FROM 
      EMPLOYEE_TABLE E
    , JSON_TABLE
    (
      E.jsondoc, 'strict $' COLUMNS
      ( 
        "id" INTEGER
      , "firstname"  VARCHAR(20)
      , "lastname"   VARCHAR(20)
      , "phoneno"    VARCHAR(20)
      ) ERROR ON ERROR
    ) AS U;