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

问题描述

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

我这里有这张桌子:

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)
);

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

感谢任何帮助。

解决方法

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

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

请检查下面的 PostgreSQL 函数 activeAppointments(),它接受输入日期和时间并返回给定日期和时间的活动约会数。

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$;

我已经采用了上面提到的“约会”表并在下面插入了示例数据。

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