0

我正在开发基于租户密钥和其他查询条件更新批处理日志的功能。

在我的功能中,我使用连接并逐个循环记录记录,按顺序更新批处理日志。

我的代码如下

CREATE TABLE linen_tenant_header
(
    tenant_key character varying(200) NOT NULL,
    tenant_name character varying(50) NOT NULL,
    email character varying(50) NOT NULL,
    created_user character varying(200) NOT NULL,
    updated_user character varying(200),
    created_time timestamp without time zone DEFAULT now(),
    updated_time timestamp without time zone DEFAULT now()
);

CREATE TABLE linen_sc_batch_log
    (
    batch_id serial NOT NULL,
    profile_header_id integer NOT NULL,
    batch_status character varying(200),
    batch_type character varying(200) NOT NULL,
    batch_mode character varying(200) NOT NULL,
    tenant_key character varying(200) NOT NULL,
    created_user character varying(200),
    updated_user character varying(200),
    created_time timestamp without time zone DEFAULT now(),
    updated_time timestamp without time zone DEFAULT now(),
);

CREATE TABLE linen_sc_expressions
(
    expression_id integer NOT NULL,
    reference_id integer NOT NULL,
    tenant_key character varying(200) NOT NULL,
    expression_text character varying(10000) NOT NULL,
    start_date date NOT NULL,
    end_date date,
    created_user character varying(200) NOT NULL,
    updated_user character varying(200),
    created_time timestamp without time zone DEFAULT now(),
    updated_time timestamp without time zone DEFAULT now()
);

CREATE OR REPLACE FUNCTION sample_function(
    tenant_key TEXT
) RETURNS VOID AS $$
DECLARE
    rec RECORD;
BEGIN
    FOR rec IN SELECT * FROM linen_sc_batch_log bl, linen_sc_expressions sce  where bl.profile_header_id = sce.reference_id and bl.tenant_key = $1 and sce.tenant_key = $1
    LOOP
        EXECUTE FORMAT('UPDATE linen_sc_batch_log set batch_status = %L where tenant_key = %L and batch_id = %L::INTEGER', 'EXTRACTED', tenant_key, rec.batch_id);
    END LOOP;
END;
$$ LANGUAGE plpgsql;

我的功能正常工作,但我需要通过添加并行性来增强我的功能。

我不想遍历所有记录,而是想同时并行更新所有记录。

我研究了 google 和 PostgreSQL 文章,但没有找到相关的概念。

4

1 回答 1

0

我认为这可以在一条 SQL 语句中完成:

UPDATE linen_sc_batch_log AS bl
SET batch_status = 'EXTRACTED'
FROM linen_sc_expressions AS sce
WHERE bl.profile_header_id = sce.reference_id
  AND bl.tenant_key = $1 AND sce.tenant_key = $1;

如果您想要并行化,您可以在并发数据库连接上运行多个此类更新,为每个更新添加一个类似的子句。AND id % 10 = n

于 2018-10-25T11:06:29.860 回答