需要运行运行INSERT的pl / pgsql fn

时间:2014-01-15 17:33:48

标签: function postgresql database-design plpgsql sql-insert

这就是我所拥有的,我正在尝试创建一个插入fn,它将行数据基本上加载到一个已存在的表中。我还想检查特定的列数据,以确保源数据无效。

我似乎遇到的问题是让它成功运行。由于某种原因,我似乎无法让这个工作,我已经尝试了各种方式,并在网站内努力研究(一些虽然很接近,但不完全给我我需要的东西)。这基本上就是我所拥有和想要实现的目标。我知道这可能是基本的,所以提前谢谢。

CREATE OR REPLACE FUNCTION Schema.insert_fn (arg_1 character varying , arg_2 integer)
  RETURNS SETOF CHARACTER VARYING AS

$BODY$

BEGIN

--should this insert use some kind of temp table? 
     insert into <schema>.table1 (character varying, integer)
values (arg_1 character varying, arg_2 integer);

--If I wanted to run some sort of check on say arg_2
     If(select distinct (arg_2) from <schema>.table2 where invalid_date is not null)
     THEN
     raise notice 'Data has been invalidated';
END IF;
Return 'complete';
END;
$BODY$

更新

首先,它告诉我,我的回归需要'NEXT'或'QUERY'

    RETURN cannot have a parameter in function returning set; 
    use RETURN NEXT or RETURN QUERY at or near "'complete'"

一旦我这样做,当然功能将完成。但是,当我调用它时,我收到一个错误,例如:

    invalid input syntax for type boolean: "arg_1"
如果我有点模糊,我道歉。显然,我不能给你完整的arg名称上下文,因为它们与我正在做的事情有关。我感谢任何帮助。

更新

我也收到此错误:

    more than one row returned by a subquery used as an expression

我也对这个问题进行过研究,并且根本无法将任何解决方案联系起来,至少让它起作用,这意味着;当我打电话说,没有参数我收到这个错误。

更新 @ErwinBrandstetter。我说错了。我的意思是

    'col2 = arg_2 and invalid_date is NOT null' to raise an exception 

正在发生的事情是'EXIST'语句会将任何实例带到找到行的位置。我试过'WHERE EXIST'而且我收到了一个错误。我认为的问题是它们(经验证和无效的数据)共享相同的唯一ID,并且它使EXIST语句成立(我没有提供此信息)。

更新 @ErwinBrandstetter它现在运作成功。看起来我需要做的就是分开这两个条件。感谢。

    IF EXISTS (condition)
    THEN
    INSERT

    ELSEIF EXISTS (invalidated data condition)
    THEN
    RAISE EXCEPTION'DATA IS INVALIDATED';
END IF;
END;

1 个答案:

答案 0 :(得分:0)

可能会这样工作:

CREATE OR REPLACE FUNCTION schema.insert_fn (_arg1 text, _arg2 integer)
  RETURNS text AS  -- not SETOF!
$func$
BEGIN

INSERT INTO <schema>.table1 (col1, col2)  -- names here! not types
SELECT _arg1, _arg2                       -- again: names! cast only if needed
WHERE  NOT EXISTS (                       -- only if _arg2 not invalidated
   SELECT 1
   FROM   <schema>.table2
   WHERE  col2 = _arg2
   AND    invalid_date IS NOT NULL
   );

IF NOT FOUND THEN  -- No exception yet, no INSERT either --> invalidated
    RAISE EXCEPTION 'Data >>%<< has been invalidated.', _arg2;
END IF;

RETURN 'complete'::text;  -- return value probably useless

END
$func$ LANGUAGE plpgsql

最突出的错误是您声明函数返回SETOF值,而实际上只返回单个值。我可能只使用RETURNs void,因为返回值不按原样携带信息 阅读手册herehere

使用SELECTINSERT直接应用其他条件。

还有更多。请参阅上面代码中的注释。