PostgreSQL:在一个函数中插入、删除和更新的 If Else 语句

标签 postgresql stored-procedures

如何将此 SP/函数从 MySQL 转换为 PostgreSQL?

 DELIMITER $$
CREATE DEFINER=`user_name`@`%` PROCEDURE `sp_TABLE_name`(
pTransType int,
pId bigint,
pName varchar(250),
pStartFrom datetime,
pStartTo datetime,
pSignature longblob)
BEGIN

if pTransType = 1 then

    insert into TABLE_name (Id, Name, startfrom, startto, signature)    
       values(pId, pName, pStartFrom, pStartTo, pSignature);

end if;

if pTransType = 2 then

    update TABLE_name set 
            Name = pName,
            startfrom = pStartFrom,
            startto = pStartTo,
            signature  = pSignature
        where Id = pId;

end if;

if pTransType = 3 then

    delete from TABLE_name where id = pId;

end if;

END$$
DELIMITER ;

我尝试了 Case when Statement 但是,其他错误显示.. 还有其他方法吗?

最佳答案

我认为它看起来像这样:

CREATE OR REPLACE FUNCTION sp_TABLE_name(pTransType int, pId bigint, pName varchar(250),
   pStartFrom timestamp, pStartTo timestamp, pSignature bytea)
  RETURNS void AS
$BODY$
BEGIN
  if pTransType = 1 then

      insert into TABLE_name (Id, Name, startfrom, startto, signature)    
         values(pId, pName, pStartFrom, pStartTo, pSignature);

  elsif pTransType = 2 then

      update TABLE_name set 
              Name = pName,
              startfrom = pStartFrom,
              startto = pStartTo,
              signature  = pSignature
          where Id = pId;

  elsif pTransType = 3 then

      delete from TABLE_name where id = pId;

  end if;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

请注意,我确实必须使您的数据类型符合 PostgreSQL 等效项(或者我对它们的最佳猜测)。

关于PostgreSQL:在一个函数中插入、删除和更新的 If Else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41732645/

相关文章:

mysql - 如何将查询结果存储到变量中并多次使用它?

sql - 模型 M :N relationship in SQL where parent may be one of many types 的正确方法

sql - 是否可以在 postgresql 中为每个主键创建索引?

sql - PostgreSQL 基于列的条件计数

sql - PostgreSQL - 合并两个表

postgresql - Heroku 目前是否支持 postgresql 时态表扩展?

sql - 如果创建日期超过一周,则删除 SQL 表 - MS SQL Server

sql-server - 替换MSSQL中的非ascii字符

sql - 如何从 Excel VBA 脚本调用 Oracle 存储过程?

mysql - 在MySQL存储过程中创建动态查询?