I have 100s of tables having the same schema and I have a trigger function to UPDATE some column whenever data is INSERTed into that table.
Table Schema:
CREATE TABLE symbol_daily_ohlc (
cdate date,
open numeric(8,2),
high numeric(8,2),
low numeric(8,2),
close numeric(8,2),
sma8 numeric(8,2)
);
Trigger function:
create or replace function update_sma8() RETURNS TRIGGER AS
$$
BEGIN
UPDATE symbol_daily_ohlc d SET sma8 = s.simple_mov_avg
FROM
(
SELECT sec.cdate,AVG(sec.close)
OVER(ORDER BY sec.cdate ROWS BETWEEN 7 PRECEDING AND CURRENT ROW) AS
simple_mov_avg FROM symbol_daily_ohlc sec
)s where s.cdate = NEW.cdate --The newly inserted cdate
AND d.cdate = s.cdate;
RETURN NULL;
END $$ language plpgsql;
Trigger setup on table:
CREATE TRIGGER trig_update_sma
AFTER INSERT ON symbol_daily_ohlc
FOR EACH ROW
EXECUTE PROCEDURE update_sma8();
This is working well for the given table i.e symbol_daily_ohlc. I would like to use the same trigger function i.e update_sma8() to be used with any table having the same schema (I don't want to rewrite the same function for different tables).
I tried replacing the table name (i.e symbol_daily_ohlc) with TG_TABLE_NAME, but that didn't work - thrown errors. So how to do that?
Reference: SQL trigger function to UPDATE daily moving average upon INSERT
CREATE VIEW msft_history AS SELECT * FROM all_stock_history WHERE stock_symbol = 'MSFT';CREATE VIEW goog_history AS SELECT * FROM all_stock_history WHERE stock_symbol = 'GOOG'UPDATEassign the values you want to the respective columns of thenewpseudo record. Then you won't have a table name in the trigger body and can use it for every table that has the columns you address (with compatible types of course).