0
私は関数に渡された条件付きパラメータを動的に追加する必要があるPostgres関数を持っています。ここでは機能があります:for_staff_id
が関数に渡され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...IN
ループに位置し、クエリに条件(WHERE staff_id = for_staff_id
)として追加する必要があります。私はFOR...IN
の中でIF/ELSE
を実行しようとしましたが、構文エラーが発生しています。
これを行うより良い方法はありますか?
ありがとうございます!
私はPostgres 9.5を実行しています。
'coalesce(staff_id = for_staff_id、true)'がチケットでした!ありがとう、@redneb:D – jdixon04