Below is a small code of parsing a json array into a table in a database:
CREATE TEMPORARY TABLE json_import (doc json) ON COMMIT DROP;
INSERT INTO json_import (doc) VALUES(
'[
{
"cli_nk": 1,
"effective_from_date": "2021-01-18",
"effective_to_date": "",
"user_dml_type_code": "U",
"user_fix_desc": "qwert"
},
{
"cli_nk": 2,
"effective_from_date": "2023-03-25",
"effective_to_date": "",
"user_dml_type_code": "I",
"user_fix_desc": "qwe"
},
{
"cli_nk": 4,
"effective_from_date": "2015-07-18",
"effective_to_date": "2999-12-31",
"user_dml_type_code": "D",
"user_fix_desc": "ytrewq"
},
{
"cli_nk": 5,
"effective_from_date": "2016-08-03",
"effective_to_date": "2999-12-31",
"user_dml_type_code": "U",
"user_fix_desc": "zxc"
}
]'
);
INSERT INTO user_type (cli_nk, effective_from_date, effective_to_date, user_dml_type_code, user_fix_desc)
SELECT
NULLIF (p.cli_nk, ''),
NULLIF (p.effective_from_date, ''),
NULLIF (p.effective_to_date, ''),
NULLIF (p.user_dml_type_code, ''),
NULLIF (p.user_fix_desc, '')
FROM json_import l
CROSS JOIN LATERAL json_populate_recordset(NULL::user_type, doc) AS p;
DDL of my user_type table:
CREATE TABLE public.user_type (
cli_nk text NULL,
effective_from_date date NULL,
effective_to_date date NULL,
user_dml_type_code bpchar(1) NOT NULL,
user_fix_desc text NULL
);
But after I try to execute it, I get the following error:
SQL Error [22007]: ERROR: invalid syntax for date type: "" Position: 180
How can I handle this error and fill the table correctly?
NULLIF returns the datatype that is used as input, in your case TEXT. You must cast the result from NULLIF to the desired data type, in your case a DATE: