【问题标题】:Database function that takes as input date and time以日期和时间为输入的数据库函数
【发布时间】:2021-07-23 08:25:57
【问题描述】:

在这里寻找一些关于 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 postgresql stored-procedures sql-function


    【解决方案1】:

    请检查下面的 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', '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
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2021-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-06
        • 1970-01-01
        相关资源
        最近更新 更多