简体   繁体   中英

How to insert value into table from auto-increment value in other table : postgressql (update and insert two table)

I am trying to insert the value "stock_id_artc" int4 into table "tbl_stock" from auto increment inserted value "artc_id" in table "tbl_artc" :

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

the solution :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM