0

I have two tables (in postgres) - ads and logs. After every insert into logs table, depending on the action it should increment the count of a column in the ads table.

I have tried to write a function which the trigger will call, but it throws a error while trying to create the function. I am new to postgresql triggers and function, so can someone point out what is wrong with this.

create function update_ad_count (action character(4), ad_id INT) returns void 
as $$case when action='VIEW' then
(UPDATE ads SET views = (SELECT views+1 FROM ads WHERE id=ad_id), updated = now() WHERE id=ad_id;)
end;$$
language sql

The error I get is

ERROR:  syntax error at or near "case"
LINE 2: as $$case when action=\'VIEW\' then
             ^

Update: @Tomalak: Thanks for the function and updating the update statement (couldn't resist the pun).

I learnt after lot of googling, that the function shouldn't have any params and use NEW.col_name and should return a TRIGGER.

4
  • I'm not sure what a function that returns a trigger is. In my understanding, triggers are defined and not returned by functions, but then again I don't know very much about postgres, so I'm glad I got the UPDATE statement right at least. ;-) Commented Jan 26, 2009 at 19:18
  • Care to update my answer with your findings, so others that come here through Google find something they can use immediately? Commented Jan 26, 2009 at 19:18
  • @Tomalak, if you want to know more about the pseudo-type TRIGGER see postgresql.org/docs/8.3/interactive/trigger-definition.html If you still want more info you can ask a new SO question and I'll provide a detailed answer there. Commented Jan 26, 2009 at 20:49
  • Oh damn, you can't yet edit other people's posts (sorry I forgot). You can edit your working sample into your own question though. Commented Jan 26, 2009 at 22:06

2 Answers 2

2

First off, your UPDATE call should be:

UPDATE ads SET views = views + 1, updated = NOW() WHERE id = ad_id;

According to the documentation, something like this should do it:

CREATE FUNCTION update_ad_count (action CHARACTER(4), ad_id INT) 
RETURNS VOID
AS $$ 
BEGIN
  IF action = 'VIEW' THEN
    UPDATE ads SET views = views + 1, updated = NOW() WHERE id = ad_id;
  END IF;
END;
$$ LANGUAGE plpgsql;

CASE is not a flow-control statement, it cannot be used like an IF statement. It is a value-producing statement (an expression) and must be used as such, e.g. you must SELECT/UPDATE from it.

Sign up to request clarification or add additional context in comments.

Comments

0

I'm not hugely familiar with postgresql, but based on what I do know... shouldn't it be "$$ case" instead of "$$case"?

1 Comment

The extra space doesn't work. I think $$ is just an alternative to quote '. It can be used without any space.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.