【发布时间】:2016-09-20 05:27:33
【问题描述】:
我有一个 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 循环中的查询中。我尝试在FOR...IN 中执行IF/ELSE,但出现语法错误。
有没有更好的方法来做到这一点?
谢谢!
请注意,我正在运行 Postgres 9.5。
【问题讨论】:
标签: sql postgresql