PostgreSQL-存储过程

存储过程其实就是函数,由一组 sql 语句组成,实现比较复杂的数据库操作;

存储过程 是 存储在 数据库服务器 上的,用户可以像调用 sql 自带函数一样 调用存储过程

PostgreSQL-存储过程

语法解析

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;

很容易理解,不多解释

下面我对一张表进行简单操作,逐步递进的介绍存储过程的语法

步骤1-基础版

PostgreSQL-存储过程

into 表示把结果赋值给 后面的变量,该变量必须在 declare 提前声明

调用存储过程

select mycount3()

步骤2-把 sql 语句赋给变量

create or replace function mycount3()
returns integer as $$

declare
 mysql text;
 counts integer;

begin
mysql:=‘select count("CD_ID") from "CDS"‘;
execute mysql into counts;
return counts;
end;

$$ language plpgsql;

步骤3-带变量,且 sql 语句用字符串拼接

create or replace function mycount4(tableName text, columnName text)
returns text as $$

declare
 mysql text;

begin
mysql:=‘select count(‘
    || quote_ident(columnName) 
    || ‘) from ‘
    || quote_ident(tableName);

return mysql;

end;

$$ language plpgsql;

1. 函数的参数必须声明类型

2. || 表示字符串拼接符号

3. 存储过程中的对象不能直接引用变量,要用 quote_ident,它会把变量 转换成 合适的 对象

4. 在 sql 语句中,大写,全部会变成小写,如果想保留大写,需要加 双引号

调用存储过程

select mycount4(‘CDS‘, ‘CD_ID‘);

返回

select count("CD_ID") from "CDS"

可以看到,输入参数是单引号,经过 quote_ident 后,自动变成双引号,保留了大写

步骤4-换一种拼接方式,并且函数体加了 if 判断

create or replace function mycount4(tableName text, columnName text)
returns integer as $$

declare
 mysql text;
 counts integer;

begin
mysql:=‘select count("‘ || $2 || ‘") from "‘ || $1 || ‘" ‘;
execute mysql into counts using tableName, columnName;

if counts > 100 then
    return counts;
else return 1;
end if;

end;

$$ language plpgsql;

1. 用 using 调取变量,此时需要自己加 双引号 以保留 大写

2. $1 $2 对应的是函数的参数位置,跟 using 后的顺序无关

3. if 后面有个 then

4. text 可变长度字符串

参考资料:

https://www.yiibai.com/postgresql/postgresql-functions.html

https://www.cnblogs.com/ssqhan/p/7289931.html#top

相关推荐