postgres:函数查询中的动态条件

时间:2016-09-19 21:25:05

标签: sql postgresql

我有一个Postgres函数,如果将条件参数传递给函数,我需要动态添加它。这是功能:

CREATE OR REPLACE FUNCTION public.get_appointments(
     for_business_id INTEGER,
     range_start DATE,
     range_end   DATE,
     for_staff_id INTEGER
    )
       RETURNS SETOF appointment
       LANGUAGE plpgsql STABLE
       AS $function$
     DECLARE
        appointment appointment;
        recurrence  TIMESTAMP;
        appointment_length INTERVAL;
        parent_id UUID;
     BEGIN
        FOR appointment IN
            -- NEED TO CONDITIONALLY ADD "WHERE staff_id = for_staff_id" 
            -- if for_staff_id is NOT NULL
            SELECT *
              FROM appointment
             WHERE business_id = for_business_id
               AND (
                       recurrence_pattern IS NOT NULL
                   OR  (
                          recurrence_pattern IS NULL
                      AND starts_at BETWEEN range_start AND range_end
                   )
               )
         LOOP
            IF appointment.recurrence_pattern IS NULL THEN
              RETURN NEXT appointment;
              CONTINUE;
            END IF;

            appointment_length := appointment.ends_at - appointment.starts_at;
            parent_id := appointment.id;

            FOR recurrence IN
                SELECT *
                  FROM generate_recurrences(
                           appointment.recurrence_pattern,
                           appointment.starts_at,
                           range_start,
                           range_end
                  )
            LOOP
                EXIT WHEN recurrence::date > range_end;
                CONTINUE WHEN (recurrence::date < range_start AND recurrence::date > range_end) OR recurrence = ANY(appointment.recurrence_exceptions);
                appointment.id := uuid_generate_v5(uuid_nil(), parent_id::varchar || recurrence::varchar);
                appointment.parent_id := parent_id;
                appointment.starts_at := recurrence;
                appointment.ends_at := recurrence + appointment_length;
                appointment.recurrence_pattern := appointment.recurrence_pattern;
                appointment.recurrence_exceptions := NULL;
                appointment.is_recurrence := true;
                RETURN NEXT appointment;
            END LOOP;
        END LOOP;
        RETURN;
     END;
    $function$;

如果将for_staff_id传递给函数,我需要将其作为条件(WHERE staff_id = for_staff_id)添加到位于FOR...IN循环中的查询中。我已尝试在IF/ELSE内执行FOR...IN,但我收到了语法错误。

有更好的方法吗?

谢谢!

请注意,我正在运行Postgres 9.5。

1 个答案:

答案 0 :(得分:1)

只需添加以下内容

即可
... AND (for_staff_id IS NULL OR staff_id = for_staff_id)

或者

... AND coalesce(staff_id = for_staff_id, true)

WHERE语句的SELECT子句中。

相关问题