以日期和时间作为输入的数据库函数

Database function that takes as input date and time

在此寻找有关 SQL 函数的一些指导。

我这里有这个table:

CREATE TABLE appointments
(
    patient varchar(20) NOT NULL,
    doctor varchar(20) NOT NULL,
    apt_date date NOT NULL,
    apt_start time NOT NULL,
    apt_end time NOT NULL,

    CONSTRAINT pk_appointments PRIMARY KEY (patient, apt_date)
);

我正在寻找一个函数,该函数将日期和时间作为输入,returns 在给定日期和时间激活的约会数量。

感谢任何帮助。

为什么是函数?一个简单的 SQL 查询似乎就足够了:

select count(*)
from appointments
where apt_date = date '2021-04-30'
  and time '14:00' between apt_start and apt_end

请检查下面的 PostgreSQL 函数 activeAppointments(),它接受输入日期和时间以及 returns 在给定日期和时间激活的约会数量。

CREATE OR REPLACE FUNCTION public.activeappointments(
    ondate date,
    fromtime time without time zone,
    totime time without time zone)
    RETURNS integer
    LANGUAGE plpgsql
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
declare
    total integer;
BEGIN
   SELECT count(*) into total FROM appointments 
   where apt_date = ondate and apt_start >= fromTime and apt_end <= toTime;
   RETURN total;
END;
$BODY$;

我已经接受了上面提到的“约会”table,并在其中插入了以下示例数据。

insert into appointments values ('Patient001', 'Doc001', '01-JAN-2021','120000','130000');
insert into appointments values ('Patient002', 'Doc001', '01-JAN-2021','133000','143000');
insert into appointments values ('Patient003', 'Doc001', '01-JAN-2021','150000','160000');
  • 插入的记录总数 3.
select count(1) from appointments; 
  • 要运行函数,请使用下面的脚本。
SELECT activeAppointments('01-JAN-2021', '120000', '150000'); --2