What is the proper syntax for PostgreSQL stored procedures (functions)?

风格不统一 提交于 2020-01-03 15:32:50

问题


I'm trying to write two types of stored procedures in PostgreSQL. From what I understand Postgre only has functions. I was wondering if someone can take a look at my code and offer pointers. Also, I'm am not familiar whether with the spacing/new lines of commands.

The first function needs to take input from user and add it onto a table. Suppose we have a table name "Car" with attributes "model" and "year". Will this be a correct stored function to add a new car to the table?

CREATE OR REPLACE FUNCTION
    addto_car(model IN Car.model%type, year IN Car.year%type)
RETURNS
    void
AS $$
BEGIN
    INSERT INTO Car VALUES(model, year);
END;
$$ LANGUAGE plpgsql; (#Is this correct? I'm using postgresql 9)

---------- Work in Progress code Function 1

CREATE OR REPLACE FUNCTION
    addto_car(In model Car.model%type, IN year Car.year%type)
AS $$
BEGIN
    INSERT INTO Car VALUES(model, year);
END;
$$ LANGUAGE plpgsql;

This now works! (inserts values model and year into Car).


回答1:


From the Official Documentation

CREATE [ OR REPLACE ] FUNCTION
    name ( [ [ argmode ] [ argname ] argtype [ { DEFAULT | = } default_expr ] [, ...] ] )
    [ RETURNS rettype
      | RETURNS TABLE ( column_name column_type [, ...] ) ]
  { LANGUAGE lang_name
    | WINDOW
    | IMMUTABLE | STABLE | VOLATILE
    | CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT
    | [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY DEFINER
    | COST execution_cost
    | ROWS result_rows
    | SET configuration_parameter { TO value | = value | FROM CURRENT }
    | AS 'definition'
    | AS 'obj_file', 'link_symbol'
  } ...
    [ WITH ( attribute [, ...] ) ]

You will find your answer there and, maybe, learn two or three useful things on the process.

You might be particularly interested in the RETURNS TABLE construct.



来源:https://stackoverflow.com/questions/7013811/what-is-the-proper-syntax-for-postgresql-stored-procedures-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!