trigger function to replace insert with update

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • whsdu
    New Member
    • Dec 2011
    • 3

    trigger function to replace insert with update

    This is a really simple question and I'v been working on it for 2 hours........

    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;
    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:
    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;
    And below is my trigger:
    Code:
    CREATE TRIGGER update_or_insert
      BEFORE INSERT
      ON download
      FOR EACH ROW
      EXECUTE PROCEDURE download_counter();
    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.
  • rski
    Recognized Expert Contributor
    • Dec 2006
    • 700

    #2
    You can also use writeable CTE if you use postgres 9.1
    See here
    There is always discussion of having UPSERT/MERGE in postgresql. Since, oracle and other RDBMS has this feature, therefore people ask about this feature in PostgeSQL. In previous version of Postgre…

    Comment

    • whsdu
      New Member
      • Dec 2011
      • 3

      #3
      Thanks for your reply.
      I would like to integrate the sql into my code,such as:

      insert into download (weeknumber, singerid, counter) values ((SELECT EXTRACT(WEEK FROM (SELECT CURRENT_TIMESTA MP))), ?, 1)

      so, I can do it with sql on the console, but I have no idea how to integrate the "WITH upsert as" statement into my code.

      Comment

      Working...