Как создать представление в SQL, которое принимает параметры - PullRequest
0 голосов
/ 16 апреля 2019

Я хочу создать представление, которое принимает параметры, а затем сделать выбор в этом представлении, как это

CREATE OR REPLACE FUNCTION statistiquess(dateDeb date, dateFin date)
RETURNS void AS
$$
     CREATE OR REPLACE VIEW statistics 
     AS 
      SELECT 
         e.matricule_ens, 
         e.nom_ens, 
         e.prenom_ens, 
         m.code_matiere, 
         m.nom_matiere, 
         f.id_formation, 
         f.nom_formation, 
         SUM ((CAST (c.heure_fin AS TIME))-(CAST (c.heure_deb AS TIME))) AS heure_total_programme, 
         SUM ((CAST (c.heure_dep_ens AS TIME))-(CAST (c.heure_arr_ens AS TIME))) AS heure_total_enseigne 
     FROM 
         enseignant e inner join cours c on e.matricule_ens = c.matricule_ens 
         inner join matiere m on c.code_matiere =  m.code_matiere 
         inner join formation f on f.id_formation = c.id_formation 
     WHERE
       c.jour between dateDeb and dateFin
     GROUP BY 
        e.matricule_ens, m.code_matiere, f.id_formation 
     ORDER BY 
        e.nom_ens;
$$
LANGUAGE SQL;

У меня появляется эта ошибка, когда я пытаюсь выбрать все из функций, подобных этой

select * from statistiquess('2019-03-06', '2019-03-29');

ERREUR: la colonne «datedeb» n'existe pas

LINE 6: ..._formation = c.id_formation where (c.jour between datedeb an...


QUERY:  
     CREATE OR REPLACE VIEW statistics AS select e.matricule_ens, e.nom_ens, e.prenom_ens, m.code_matiere, m.nom_matiere, f.id_formation, f.nom_formation, 
     SUM ((CAST (c.heure_fin AS TIME))-(CAST (c.heure_deb AS TIME))) AS heure_total_programme, 
     SUM ((CAST (c.heure_dep_ens AS TIME))-(CAST (c.heure_arr_ens AS TIME))) AS heure_total_enseigne 
     from enseignant e inner join cours c on e.matricule_ens = c.matricule_ens inner join matiere m on c.code_matiere =  m.code_matiere 
     inner join formation f on f.id_formation = c.id_formation where (c.jour between datedeb and datefin) 
     GROUP BY e.matricule_ens, m.code_matiere, f.id_formation ORDER BY e.nom_ens;

Ответы [ 2 ]

1 голос
/ 17 апреля 2019

Синтаксис, который вы имеете выше, имеет function не такой вид, как в заголовке.Только функции и хранимые процедуры могут принимать параметры.функция возвращает значение, а хранимые процедуры - нет.синтаксис для функции равен

CREATE [OR REPLACE] FUNCTION function_name (arguments) 
RETURNS return_datatype AS $variable_name$
   DECLARE
      declaration;
      [...]
   BEGIN
      < function_body >
      [...]
      RETURN { variable_name | value }
   END; LANGUAGE plpgsql;

синтаксис для хранимой процедуры

CREATE [OR REPLACE] PROCEDURE procedure_name(parameter_list)
LANGUAGE language_name
AS $$
    stored_procedure_body;
$$;

представление - это хранимый запрос, который выможно запросить, как и любую другую таблицу.

SELECT * FROM statistiquess WHERE c.jour BETWEEN '2019-03-06' AND '2019-03-29';   

, не понимая ваших данных и прецедентов, трудно сказать, какую вы должны использовать.Исходя из вашего вопроса, это звучит так, как будто вам нужен либо просмотр, либо хранимая процедура.

0 голосов
/ 17 апреля 2019

Вам не нужно создавать представление внутри функции, чтобы сделать это. Просто верните результат запроса из функции:

CREATE OR REPLACE FUNCTION statistiquess(dateDeb date, dateFin date)
RETURNS tables (matricule_ens text, nom_ens text, prenom_ens text, 
               code_matiere text, nom_matiere text, id_formation int,
               nom_formation text, heure_total_programme bigint, 
               heure_total_enseigne bigtin) AS
$$
    SELECT 
       e.matricule_ens, 
       e.nom_ens, 
       e.prenom_ens, 
       m.code_matiere, 
       m.nom_matiere, 
       f.id_formation, 
       f.nom_formation, 
       SUM ((CAST (c.heure_fin AS TIME))-(CAST (c.heure_deb AS TIME))) AS heure_total_programme, 
       SUM ((CAST (c.heure_dep_ens AS TIME))-(CAST (c.heure_arr_ens AS TIME))) AS heure_total_enseigne 
    FROM 
       enseignant e inner join cours c on e.matricule_ens = c.matricule_ens 
       inner join matiere m on c.code_matiere =  m.code_matiere 
       inner join formation f on f.id_formation = c.id_formation 
    WHERE
     c.jour between dateDeb and dateFin
    GROUP BY 
      e.matricule_ens, m.code_matiere, f.id_formation 
    ORDER BY 
      e.nom_ens;
$$
LANGUAGE SQL;

Вам нужно будет настроить типы данных возвращаемых столбцов (внутри части table (...)) - я только догадывался, какими они могут быть.

Тогда вы можете использовать его как «представление с параметрами»:

select * 
from statistiquess('2019-03-06', '2019-03-29');
...