This is a really simple question and I'v been working on it for 2 hours........
The table is:
and what I want to do is whenever I want to insert a new record ,if the combination of songid and weeknumber is exist the counter add one otherwise execute the insert.
The trigger function I make is:
And below is my trigger:
Since I cannot find replace in postgresql ,I think maybe I misused the return type.
Thanks very much for anyone who can give me some advices.
The table is:
Code:
CREATE TABLE download
(
id integer NOT NULL DEFAULT nextval('seq'::regclass),
songid integer NOT NULL,
counter integer NOT NULL,
weeknumber integer NOT NULL,
CONSTRAINT download_pkey PRIMARY KEY (id ),
CONSTRAINT download_songid_fkey FOREIGN KEY (songid)
REFERENCES song (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE download
OWNER TO postgres;
The trigger function I make is:
Code:
CREATE OR REPLACE FUNCTION download_counter() RETURNS trigger AS $BODY$ DECLARE tmpid INTEGER; BEGIN SELECT id INTO tmpid FROM download WHERE songid=NEW.songid AND weeknumber=NEW.weeknumber; IF NOT FOUND THEN RETURN NEW; ELSE UPDATE download SET counter=counter+1 WHERE id=NEW.id; RETURN NEW; END IF; END; $BODY$ LANGUAGE plpgsql VOLATILE COST 100; ALTER FUNCTION download_counter() OWNER TO postgres;
Code:
CREATE TRIGGER update_or_insert BEFORE INSERT ON download FOR EACH ROW EXECUTE PROCEDURE download_counter();
Thanks very much for anyone who can give me some advices.
Comment