如何处理PL / pgSQL函数中的应用程序设置的有效方法

时间:2014-06-25 06:52:58

标签: sql postgresql plpgsql

考虑以下情况:我有PL / pgSQL函数检查,如果给定审计员有QS审计员功能的一些先决条件。此先决条件的阈值在单独的表quasar_settings中定义。每次,If都是被调用的函数,执行SELECT来检索这些先决条件。这是非常低效的,因为每行都会调用此SELECT。此quasar_settings表仅包含一行。还有其他更有效的解决方案(全局变量,缓存等)吗?

表quasar_settings只有一行。 使用PostgreSQL 9.3

PL / pgSQL功能

CREATE OR REPLACE FUNCTION qs_auditor_training_auditing(auditor quasar_auditor) RETURNS boolean AS $$
DECLARE
    settings quasar_settings%ROWTYPE;
BEGIN
    SELECT s INTO settings
    FROM quasar_settings s LIMIT 1;
    RETURN auditor.nb1023_procedures_hours >= settings.qs_auditor_nb1023_procedures AND
           -- MD Training
           auditor.mdd_hours +  auditor.ivd_hours >= settings.qs_auditor_md_training AND
            -- ISO 9001 Trainig
           (
            auditor.is_aproved_for_iso13485 OR
            (auditor.is_aproved_for_iso9001 AND auditor.iso13485_hours >= settings.qs_auditor_iso13485_training) OR
            (auditor.iso13485_hours + auditor.iso9001_hours >= settings.qs_auditor_class_room_training)
           );
END;
$$ LANGUAGE plpgsql;

使用示例

SELECT auditor.id, qs_auditor_training_auditing(auditor) FROM quasar_auditor auditor;

1 个答案:

答案 0 :(得分:2)

交叉连接到设置表而不是在每一行调用该函数

select
    a.id,
    a.nb1023_procedures_hours >= s.qs_auditor_nb1023_procedures and
    -- md training
    a.mdd_hours + a.ivd_hours >= s.qs_auditor_md_training and
     -- iso 9001 trainig
    (
        a.is_aproved_for_iso13485 or
        (
            a.is_aproved_for_iso9001 and
            a.iso13485_hours >= s.qs_auditor_iso13485_training
        ) or
        (a.iso13485_hours + a.iso9001_hours >= s.qs_auditor_class_room_training)
    )
from
    quasar_auditor a
    cross join
    quasar_settings s