Home > Software design >  Trigger insert of data into table with result from another select query
Trigger insert of data into table with result from another select query

Time:12-28

Starting my first steps in SQL.

I'm trying to insert the last row of a timestamped table to another table.

I've written this trigger:

CREATE TRIGGER update_analysis()
AFTER INSERT ON data
FOR EACH ROW
    EXECUTE PROCEDURE insert_to_analysis();

I've defined a function, which I know is wrong, but don't understand how to write it correctly. (the target table has these columns)

CREATE FUNCTION UPDATE_ANALYSIS() RETURNS TABLE
AS
$$ BEGIN
INSERT INTO ANALYSIS (TIME, CYCLE_NUMBER,CAT1,CAT2,CAT3)
SELECT (TIME, CYCLENO , I1 , I2 * 2 ,I3*3)
FROM DATA
ORDER BY TIME DESC
LIMIT 1;)

RETURN 
END;

$$ LANGUAGE 'plpgsql';

Thanks in advance

CodePudding user response:

If you are referencing the same data you just inserted into data, you could simply refer to what you inserted instead of SELECT:ing, like so:

CREATE FUNCTION UPDATE_ANALYSIS() RETURNS TABLE
AS
$$ BEGIN
INSERT INTO ANALYSIS (TIME, CYCLE_NUMBER,CAT1,CAT2,CAT3)
VALUES (NEW.TIME, NEW.CYCLENO , NEW.I1 , NEW.I2 * 2 ,NEW.I3 * 3);


RETURN NEW;
END;

$$ LANGUAGE 'plpgsql';

CodePudding user response:

Since it's a function for a trigger, it should return a trigger.

And it's for each row, so an insert from values is possible.

Example

CREATE FUNCTION FN_INSERT_TO_ANALYSIS() RETURNS TRIGGER
AS $ins_analysis$ 
BEGIN
  INSERT INTO ANALYSIS (TIME, CYCLE_NUMBER, CAT1, CAT2, CAT3)
  VALUES (NEW.TIME, NEW.CYCLENO, NEW.I1, NEW.I2 * 2 , NEW.I3 * 3);
RETURN NEW;
END $ins_analysis$ LANGUAGE 'plpgsql';
CREATE TRIGGER trg_data_ins_analysis
AFTER INSERT ON data
FOR EACH ROW
EXECUTE PROCEDURE fn_insert_to_analysis();
insert into data values (current_timestamp,1,1,1,1)
select * from data
time cycleno i1 i2 i3
2021-12-27 14:53:17.822649 1 1 1 1
select * from ANALYSIS
time cycle_number cat1 cat2 cat3
2021-12-27 14:53:17.822649 1 1 2 3

Demo on db<>fiddle here

  • Related