Call row_to_json(row) on any PostgreSQL statement (even statements that don't return a result)

前端 未结 2 1713
逝去的感伤
逝去的感伤 2021-01-26 08:49

I\'m looking for query to always return the JSON representation from PostgreSQL statement, even if there\'s no returning *. Here\'s an example:

WITH         


        
相关标签:
2条回答
  • 2021-01-26 09:25

    I think the problem doesn't have anything to do with your usage of row_to_json, but rather trying to embed an INSERT statement into a CTE. The following code ran without problem on my Postgres:

    WITH result AS (VALUES ('matt', 33), ('drew', 42))
    select row_to_json(row) from result as row;
    

    which output this:

    "{"column1":"matt","column2":33}"
    "{"column1":"drew","column2":42}"
    

    You should either use CTE without INSERT, or first make the INSERT into your users table and then create the CTE afterwards.

    0 讨论(0)
  • 2021-01-26 09:29

    Use returning to get results of insert statement:

    with result as (
        insert into users("name", age) 
        values('drew', 42)
        returning *
    )
    select row_to_json(row) 
    from result as row;
    
    0 讨论(0)
提交回复
热议问题