0
CREATE FUNCTION update_status() RETURNS TRIGGER AS ' 
BEGIN 
SELECT status FROM animals
IF status = "Alive" 
THEN 
UPDATE animals SET status = "Sold" WHERE status="Alive";   
END IF;   
RETURN NULL; 
END; ' LANGUAGE plpgsql;  

CREATE TRIGGER updatetrigger AFTER UPDATE OF id_selling ON animals EXECUTE PROCEDURE     update_status(); 

It says I'm not using the selected attributes, and I should use Perform instead of Select. But then it doesnt recognize the IF after the perform. I'm really new to these syntax, so it might be wrong. I think its clear what I want to do (and i believe it simple for someone with experience). Can you please help me with this problem?

1
  • Forgot to say its creating the trigger properly, the problem is when i update the id_selling variable. Commented Nov 12, 2012 at 18:38

1 Answer 1

4

In standard SQL (and PostgreSQL), this is a quoted identifier (table name, column name, ...):

"Alive"

and this is a string literal:

'Alive'

You will be getting complaints about "unknown columns" because you're using the wrong quotes for your strings.

Functions are usually defined with dollar-quoting to avoid this sort of thing:

CREATE FUNCTION update_status() RETURNS TRIGGER AS $$
BEGIN 
    SELECT status FROM animals
    IF status = 'Alive' THEN 
        UPDATE animals SET status = 'Sold' WHERE status = 'Alive';   
    END IF;   
    RETURN NULL; 
END;
$$ LANGUAGE plpgsql;

Triggers have access to NEW and OLD to represent the previous/current state of the row and the new/updated state of the row, you should be consulting those instead of trying to SELECT to find the status:

CREATE FUNCTION update_status() RETURNS TRIGGER AS $$
BEGIN 
    IF NEW.status = 'Alive' THEN 
        UPDATE animals SET status = 'Sold' WHERE status = 'Alive';   
    END IF;   
    RETURN NULL; 
END;
$$ LANGUAGE plpgsql;

You might want a little more in the WHERE clause for that UPDATE too, just WHERE status = 'Alive' seems a bit broad.

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

2 Comments

I recently compiled a list for which delimiters to use for identifiers in this related answer.
This helped me a lot, TYVM! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.