如果记录存在则创建函数,然后在postgres中运行一些代码

时间:2017-09-01 11:48:41

标签: postgresql plpgsql

我需要运行一个运行一堆INSERT个查询的函数。唯一的问题是我需要确保这个过程尚未发生。问题是我在if then语句中无法正确获取语法。

CREATE OR REPLACE FUNCTION process.copyhalsetup_tonewitem(
integer,
integer)
RETURNS void AS
$BODY$
DECLARE

pItemID_Copy_From   ALIAS FOR $1;
pItemID_Copy_Too    ALIAS FOR $2;

BEGIN

IF SELECT EXISTS(SELECT 1 
FROM process.rmt_revs 
WHERE rmt_revs.item_id =  pItemID_Copy_Too) THEN
 raise notice 'a record exists. Code not executed';
 ELSE
 --a slew of INSERT statements
END IF



END;
$BODY$
 LANGUAGE plpgsql VOLATILE
  COST 100;
  ALTER FUNCTION process.copyhalsetup_tonewitem(integer, integer)
  OWNER TO postgres;
COMMENT ON FUNCTION process.copyhalsetup_tonewitem(integer, integer) IS 'This function is used to copy from an existing item HAL data to a new like item for which there may be a new item rev or item number change.  CAUTION: Only use this for NON-FAMILY MOLDS!!!';

1 个答案:

答案 0 :(得分:1)

尝试:

IF (SELECT count(1) 
FROM process.rmt_revs 
WHERE rmt_revs.item_id =  pItemID_Copy_Too) > 0 THEN

否则如果您想要EXISTS,请添加括号:

IF (SELECT EXISTS(SELECT 1 
FROM process.rmt_revs 
WHERE rmt_revs.item_id =  pItemID_Copy_Too)) THEN

或者你最初想要的东西:

IF EXISTS(SELECT 1 
FROM process.rmt_revs 
WHERE rmt_revs.item_id =  pItemID_Copy_Too) THEN

这个想法是在IF

旁边加上布尔值