如何从其他表中的自动递增值向表中插入值:postgressql(更新并插入两个表)

时间:2019-12-06 07:38:21

标签: postgresql function auto-increment insert-update multiple-tables

我正在尝试从表“ tbl_artc”中的自动增量插入值“ artc_id”中将值“ stock_id_artc” int4插入表“ tbl_stock”中:

CREATE OR REPLACE FUNCTION "public"."update_artc"("_artc_id" int4, "_artc_name" varchar, "_artc_fourn" int4, "_artc_sector" int4, "_stock_min" int4)
      RETURNS "pg_catalog"."void" AS $BODY$
        -- Routine body goes here...

        DECLARE 
        BEGIN 
            UPDATE tbl_artc SET 
                    artc_name = _artc_name,artc_fourn=_artc_fourn,artc_sector=_artc_sector
                    WHERE artc_id = _artc_id ; 
    IF NOT FOUND THEN 
            INSERT INTO tbl_artc(artc_name,artc_fourn,artc_sector)
    VALUES
    (_artc_name,_artc_fourn,_artc_sector);
            END IF; 


    UPDATE tbl_stock
    SET stock_qt_min_alert = _stock_min
    WHERE stock_id_artc=_artc_id;
    IF NOT FOUND THEN 
    INSERT INTO tbl_stock(stock_id_artc,stock_qt_artc,stock_qt_min_alert)
    VALUES
    (artc_id,0,_stock_min);
    END IF; 

        RETURN;

    END$BODY$
      LANGUAGE plpgsql VOLATILE
      COST 100

1 个答案:

答案 0 :(得分:0)

解决方案:

CREATE OR REPLACE FUNCTION "public"."update_artc"("_artc_id" int4, "_artc_name" varchar, "_artc_fourn" int4, "_artc_sector" int4, "_stock_min" int4)
  RETURNS "pg_catalog"."void" AS $BODY$
    -- Routine body goes here...

        DECLARE tableId integer;
 BEGIN 
 UPDATE tbl_artc SET 
                artc_name = _artc_name,artc_fourn=_artc_fourn,artc_sector=_artc_sector
                WHERE artc_id = _artc_id ; 
IF NOT FOUND THEN 
        INSERT INTO tbl_artc (artc_name,artc_fourn,artc_sector) VALUES (_artc_name,_artc_fourn,_artc_sector) RETURNING artc_id INTO tableId;
        END IF; 

UPDATE tbl_stock
SET stock_qt_min_alert = _stock_min
WHERE stock_id_artc=_artc_id;
IF NOT FOUND THEN 
  INSERT INTO tbl_stock (stock_id_artc,stock_qt_artc,stock_qt_min_alert) VALUES (tableId,0,_stock_min);

END IF; 

    RETURN;

END$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100