功能MySQLPostgreSQL当前日期和时间NOW()CURRENT_TIMESTAMP当前用户CURRENT_USER()CURRENT_USER字符串长度CHAR_LENGTH(string)LENGTH(string)数学函数ABS(number), ROUND(number)ABS(number), ROUND(number)随机数天生RAND()RANDOM()子字符串SUBSTRING(string, pos, len)SUBSTRING(string FROM pos FOR len)日期加减DATE_ADD(date, INTERVAL expr unit)date + interval 'expr unit'日期格式化DATE_FORMAT(date, format)TO_CHAR(date, format) 2.4.2 语法对比
功能/特性MySQLPostgreSQL存储过程定义CREATE PROCEDURE proc_name (params) BEGIN ... END;CREATE OR REPLACE PROCEDURE proc_name (params) LANGUAGE plpgsql AS $$ BEGIN ... END; $$;函数定义CREATE FUNCTION func_name (params) RETURNS type BEGIN ... END;CREATE OR REPLACE FUNCTION func_name (params) RETURNS type LANGUAGE plpgsql AS $$ DECLARE ... BEGIN ... END; $$;参数输入、输出、输入输出参数输入参数(默认),使用IN、OUT、INOUT指定变量声明DECLARE var_name type;DECLARE var_name type; 在DECLARE块中非常处置惩罚DECLARE ... HANDLEREXCEPTION 块条件控制IF ... THEN ... ELSE ... END IF;IF ... THEN ... ELSE ... END IF;循环控制WHILE ... DO ... END WHILE;WHILE ... LOOP ... END LOOP;结果集处置惩罚SELECT ... INTO var;SELECT ... INTO var; 2.4.3 示例阐明
在MySQL中定义存储过程和函数
-- 存储过程
DELIMITER //
CREATE PROCEDURE example_procedure(IN param1 INT)
BEGIN
SELECT * FROM example_table WHERE id = param1;
END //
DELIMITER ;
-- 函数
DELIMITER //
CREATE FUNCTION example_function(param1 INT) RETURNS INT
BEGIN
DECLARE result INT;
SELECT column INTO result FROM example_table WHERE id = param1;
RETURN result;
END //
DELIMITER ;
复制代码
在PostgreSQL中转换存储过程和函数
-- 存储过程
CREATE OR REPLACE PROCEDURE example_procedure(param1 INT)
LANGUAGE plpgsql
AS $$
BEGIN
SELECT * FROM example_table WHERE id = param1;
END;
$$;
-- 函数
CREATE OR REPLACE FUNCTION example_function(param1 INT) RETURNS INT
LANGUAGE plpgsql
AS $$
DECLARE
result INT;
BEGIN
SELECT column INTO result FROM example_table WHERE id = param1;