【发布时间】:2021-12-15 23:47:49
【问题描述】:
我正在编写一个 plpgsql 函数,它应该根据提供的 JSON 对象更新表。 JSON 包含一个表表示形式,其中包含与表本身相同的所有列。
函数目前看起来如下:
CREATE OR REPLACE FUNCTION update (updated json)
BEGIN
/* transfrom json to table */
WITH updated_vals AS (
SELECT
*
FROM
json_populate_recordset(NULL::my_table, updated)
),
/* Retrieve all columns from mytable and also with reference to updated_vals table */
cols AS (
SELECT
string_agg(quote_ident(columns), ',') AS table_cols,
string_agg('updated_vals.' || quote_ident($1), ',') AS updated_cols
FROM
information_schema
WHERE
table_name = 'my_table' -- table name, case sensitive
AND table_schema = 'public' -- schema name, case sensitive
AND column_name <> 'id' -- all columns except id and user_id
AND column_name <> 'user_id'
),
/* Define the table columns separately */
table_cols AS (
SELECT
table_cols
FROM
cols
),
/* Define the updated columns separately */
updated_cols AS (
SELECT
updated_cols
FROM
cols)
/* Execute the update statement */
EXECUTE 'UPDATE my_table'
|| ' SET (' || table_cols::text || ') = (' || updated_cols::text || ') '
|| ' FROM updated_vals '
|| ' WHERE my_table.id = updated_vals.id '
|| ' AND my_table.user_id = updated_vals.user_id';
COMMIT;
END;
我注意到WITH 子句与EXECUTE 的组合总是会触发错误syntax error at or near EXECUTE,即使它们非常简单明了。是否确实如此,如果是这样,将所需变量(updated_vals、table_cols 和updated_cols)提供给EXECUTE 的替代方法是什么?
如果您对此代码有任何其他改进,我很高兴看到这些改进,因为我对 sql/plpgsql 非常陌生。
【问题讨论】:
标签: sql postgresql function