0

我有以下三个表:

create table drugs(
    id integer,
    name varchar(20),
    primary key(id)
);
create table prescription(
    id integer,
    drug_id integer,
    primary key(id),
    foreign key(drug_id) references drugs(id)
);
create table visits(
    patient_id varchar(10),
    prescription_id integer,
    primary key( patient_id , prescription_id),
    foreign key(prescription_id) references prescription(id)
);

我在这些表上编写了以下函数来显示患者的药物列表(患者 ID 是参数):

CREATE OR REPLACE FUNCTION public.patients_drugs(
    patientid character varying)
    RETURNS TABLE(drug_id integer, drug_name character varying) 
    LANGUAGE 'plpgsql'

    COST 100
    STABLE STRICT 
    ROWS 1000

AS $BODY$
begin
    create temporary table result_table(
        drug_id integer,
        drug_name varchar(20)
    );
    return  query select distinct drug.id , drug.name 
    from  visits join prescription
    on visits.patient_id = patientID;

end;
$BODY$;

但是,它给了我这个错误:

非易失性函数中不允许 CREATE TABLE

4

1 回答 1

0

您无需创建表即可“返回表”。只需摆脱 CREATE TABLE 语句。

但是您的查询也不正确,因为您正在从drug表中选择列,但您从未将其包含在FROM子句中。distinct如果您不使用连接,但使用 EXISTS 条件,您也可以去掉该子句:

CREATE OR REPLACE FUNCTION public.patients_drugs(p_patientid character varying)
    RETURNS TABLE(drug_id integer, drug_name character varying) 
    LANGUAGE plpgsql
AS $BODY$
begin
  return query 
    select d.*
    from drugs d
    where exists (select *
                  from prescription p
                    join visits v on v.prescription_id = p.id
                  where d.id = p.drug_id
                   and v.patientid = p_patientid);
end;
$BODY$;

或者更好的是,使用一个简单的 SQL 函数:

CREATE OR REPLACE FUNCTION public.patients_drugs(p_patientid character varying)
    RETURNS TABLE(drug_id integer, drug_name character varying) 
    LANGUAGE sql
AS 
$BODY$
  select d.*
  from drugs d
  where exists (select *
                from prescription p
                  join visits v on v.prescription_id = p.id
                where d.id = p.drug_id
                  and v.patientid = p_patientid);
$BODY$;
于 2019-12-27T16:18:22.010 回答