postgresql函数

准备

CREATE TABLE person (
   "id" int8,
   "name" varchar(16) COLLATE "default",
   "age" int4,
   "create_time" timestamptz(6) NOT NULL
)
WITH (OIDS=FALSE)
;

结构

CREATE OR REPLACE FUNCTION somefunc(integer, text) RETURNS integer AS $$
    --块的内容
$$ LANGUAGE plpgsql;

1 语法

[ <

2 示例

CREATE FUNCTION somefunc() RETURNS integer AS $$
<< outerblock >>--可选,当需要通过标签来访问块的变量时使用
DECLARE
    quantity integer := 30;
BEGIN
    RAISE NOTICE 'Quantity here is %', quantity;  -- Prints 30
    quantity := 50;
    DECLARE
        quantity integer := 80;
    BEGIN
        RAISE NOTICE 'Quantity here is %', quantity;  -- Prints 80
        RAISE NOTICE 'Outer quantity here is %', outerblock.quantity;  -- Prints 50
    END;

    RAISE NOTICE 'Quantity here is %', quantity;  -- Prints 50

    RETURN quantity;
END;
$$ LANGUAGE plpgsql;

声明

变量声明

name [ CONSTANT ] type [ COLLATE collation_name ] [ NOT NULL ] [ { DEFAULT | := | = } expression ];

示例

quantity integer DEFAULT 32;
url varchar := 'http://mysite.com';
user_id CONSTANT integer := 10;

记录声明

Record

基本语句

赋值

variable { := | = } expression;
示例

tax := subtotal * 0.06;

执行一个有单一行结果的查询

SELECT select_expressions INTO [STRICT] target FROM ...;
INSERT ... RETURNING expressions INTO [STRICT] target;
UPDATE ... RETURNING expressions INTO [STRICT] target;
DELETE ... RETURNING expressions INTO [STRICT] target;
示例

--查询
SELECT COUNT(0) INTO recordCount FROM person;
--插入
INSERT INTO person (id, name, age, create_time) VALUES (1, 'tom', 12, now()) RETURNING * INTO person1;
--更新
UPDATE person SET name = 'John'  WHERE id = 1 RETURNING * INTO person1;
--删除
DELETE FROM person WHERE id = 1 RETURNING * INTO person1;

执行动态命令

EXECUTE command-string [ INTO [STRICT] target ] [ USING expression [, ... ] ];
实例

  EXECUTE 'SELECT * FROM person WHERE id = $1 AND name = $2'
   INTO person1
   USING id, name;

获得结果状态

GET [ CURRENT ] DIAGNOSTICS variable { = | := } item [ , ... ];

--获取sql命令处理的行数
GET DIAGNOSTICS  dbCount = ROW_COUNT;

控制结构

函数返回

RETURN

条件

1 if条件
IF ... THEN ... ELSIF ... THEN ... ELSE ... END IF

IF number = 0 THEN
    result := 'zero';
ELSIF number > 0 THEN
    result := 'positive';
ELSIF number < 0 THEN
    result := 'negative';
ELSE
    result := 'NULL';
END IF;

2 CASE
CASE
WHEN boolean-expression THEN
statements
[ WHEN boolean-expression THEN
statements
... ]
[ ELSE
statements ]
END CASE;
示例

CASE
    WHEN x BETWEEN 0 AND 10 THEN
        msg := 'value is between zero and ten';
    WHEN x BETWEEN 11 AND 20 THEN
        msg := 'value is between eleven and twenty';
END CASE;

循环

参考连接
PL/pgSQL - SQL过程语言:http://www.postgres.cn/docs/10/plpgsql.html

你可能感兴趣的:(postgresql函数)