CREATE PROCEDURE

Synopsis

Use the CREATE PROCEDURE statement to define a new procedure in a database.

Syntax

  1. create_procedure ::= CREATE [ OR REPLACE ] PROCEDURE name (
  2. [ arg_decl [ , ... ] ] )
  3. { LANGUAGE lang_name
  4. | TRANSFORM { FOR TYPE type_name } [ , ... ]
  5. | [ EXTERNAL ] SECURITY INVOKER
  6. | [ EXTERNAL ] SECURITY DEFINER
  7. | SET configuration_parameter
  8. { TO value | = value | FROM CURRENT }
  9. | AS 'definition'
  10. | AS 'obj_file' 'link_symbol' } [ ... ]
  11. arg_decl ::= [ argmode ] [ argname ] argtype
  12. [ { DEFAULT | = } expression ]

create_procedure

CREATE PROCEDURE - 图1

arg_decl

CREATE PROCEDURE - 图2

Semantics

  • If a procedure with the given name and argument types already exists then CREATE PROCEDURE will throw an error unless the CREATE OR REPLACE PROCEDURE version is used.In that case it will replace any existing definition instead.

  • The languages supported by default are sql, plpgsql and C.

Examples

  • Set up an accounts table.
  1. CREATE TABLE accounts (
  2. id integer PRIMARY KEY,
  3. name text NOT NULL,
  4. balance decimal(15,2) NOT NULL
  5. );
  6. INSERT INTO accounts VALUES (1, 'Jane', 100.00);
  7. INSERT INTO accounts VALUES (2, 'John', 50.00);
  8. SELECT * from accounts;
  1. id | name | balance
  2. ----+------+---------
  3. 1 | Jane | 100.00
  4. 2 | John | 50.00
  5. (2 rows)
  • Define a transfer procedure to transfer money from one account to another.
  1. CREATE OR REPLACE PROCEDURE transfer(integer, integer, decimal)
  2. LANGUAGE plpgsql
  3. AS $$
  4. BEGIN
  5. IF $3 <= 0.00 then RAISE EXCEPTION 'Can only transfer positive amounts'; END IF;
  6. IF $1 = $2 then RAISE EXCEPTION 'Sender and receiver cannot be the same'; END IF;
  7. UPDATE accounts SET balance = balance - $3 WHERE id = $1;
  8. UPDATE accounts SET balance = balance + $3 WHERE id = $2;
  9. COMMIT;
  10. END;
  11. $$;
  • Transfer $20.00 from Jane to John.
  1. CALL transfer(1, 2, 20.00);
  2. SELECT * from accounts;
  1. id | name | balance
  2. ----+------+---------
  3. 1 | Jane | 80.00
  4. 2 | John | 70.00
  5. (2 rows)
  • Errors will be thrown for unsupported argument values.
  1. CALL transfer(2, 2, 20.00);
  1. ERROR: Sender and receiver cannot be the same
  2. CONTEXT: PL/pgSQL function transfer(integer,integer,numeric) line 4 at RAISE
  1. yugabyte=# CALL transfer(1, 2, -20.00);
  1. ERROR: Can only transfer positive amounts
  2. CONTEXT: PL/pgSQL function transfer(integer,integer,numeric) line 3 at RAISE

See also