Skip to content
Advertisement

Extract all records from a JSON column, using JSON type

I have a couple tables (see reproducible code at the bottom):

tbl1_have

tbl2_have

I wish to extract all json columns without providing explicit data type conversion for each columns since in my use case the names and amounts of nested attributes vary.

The expected output is the same for both cases:

tbl_want

with a_i and a_j correctly stored as a character and numeric column, which mean I’d like to map json types to SQL types (say INT and VARCHAR() here) automatically.

The following gets me half way for both tables:

How can I work around mentioning the types explicitly in with() ?


reproducible code :

Advertisement

Answer

I am assuming that you don’t know the name and type of keys in advance. You need to use dynamic SQL.

You first need to use OPENJSON without the WITH clause on the {objects} like so:

The inner query gives you the name and type of all the keys across all json values in the table. The outer query builds the WITH clause for dynamic SQL.

The rest is relatively straight forward, use the generated clause in your dynamic SQL. Here is the complete example:

Demo on db<>fiddle

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement