在Postgresql中同一张表不同行之间的全部列(不指定列)更新Update all columns (unspecified columns) between different rows

Update all columns (unspecified columns) between different rows in the same table in PostgreSQL

一、概述

需求描述: 有一张表A,需要在R2记录中列为空的情况下,更新为R1记录中的值。
Requirement description: There is a table A that needs to be updated to the value in the R1 record when the column in the R2 record is empty.

二、实现思路

1.在不确定列的情况下,首先获取表的全部列名称

In the case of uncertain columns, first obtain all column names of the table

pg_attribute中获取表的全部列:

SELECT attname FROM pg_attribute WHERE attrelid = table_name::regclass AND attnum > 0 AND NOT attisdropped';
2.判断如果为空的情况下应用R1的值

Apply the value of R1 if it is empty

用到函数COALESCE:

SELECT COALESCE(T2.COL,T1.COL) FROM T1,T2 ...
3.遍历组合更新语句

Traverse combination update statements

使用循环遍历COALESCE:

FOR col_name IN EXECUTE col_query LOOP
        update_query := update_query || ', '|| col_name || 
           ' (SELECT COALESCE(t2.' || col_name || ', t1.' || col_name || 
           ') FROM '| table_name ||' t1 WHERE t1.id = '''|| from_id || ''')';
    END LOOP;
4.完整语句

complete sentence

CREATE OR REPLACE FUNCTION update_record_by_id
(
    from_id VARCHAR, to_id VARCHAR, table_name VARCHAR
)
RETURNS VOID AS $$
DECLARE
    col_name TEXT;
    update_query VARCHAR := '';
    col_query VARCHAR := 'SELECT attname FROM pg_attribute WHERE attrelid = ''' 
    || table_name || '''::regclass AND attnum > 0 AND NOT attisdropped';
BEGIN
    FOR col_name IN EXECUTE col_query LOOP
        update_query := update_query || ', '|| col_name || 
           ' (SELECT COALESCE(t2.' || col_name || ', t1.' || col_name || 
           ') FROM '| table_name ||' t1 WHERE t1.id = '''|| from_id || ''')';
    END LOOP;

    update_query := 'UPDATE '| table_name ||' t2 SET '|| 
            substring(update_query, 3) || ' 
                WHERE t2.id = '''|| to_id ||''' 
                AND t2.id <> '''|| from_id ||'''';

    -- RAISE NOTICE 'Update Query: %', update_query;  -- 打印测试

    EXECUTE update_query;
END;
$$ LANGUAGE plpgsql;

二、应用场景·Application scenarios

在已知表名称和唯一列名称的情况下,同一表中的数据进行空值更新。

When the table name and unique column name are known, perform null value updates on data in the same table.

截图

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丷丩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值