views:

153

answers:

1

Hello, i have a problem with me trigger. Every time i insert a new line i will check if the article not sold. I can do it in the software but i think its better when the DB this does.

-- Create function
CREATE OR REPLACE FUNCTION checkSold() RETURNS TRIGGER AS $checkSold$
    BEGIN
        SELECT offer_id FROM offer WHERE offer_id = NEW.offer_id AND date_sale IS NULL;

    IF NOT FOUND THEN
        RAISE EXCEPTION 'The Offer is Sold!';
    END IF;
    RETURN NEW;
END;
$checkSold$ LANGUAGE plpgsql;


-- Create trigger
Drop TRIGGER checkSold ON tag_map;
CREATE TRIGGER checkSold BEFORE INSERT ON tag_map FOR EACH ROW EXECUTE PROCEDURE checkSold();

INSERT INTO tag_map (tag_id,offer_id) VALUES (824,80);

And this is the error after the insert.

[WARNING  ] INSERT INTO tag_map (tag_id,offer_id) VALUES (824,80)
            ERROR:  query has no destination for result data
            HINT:  If you want to discard the results of a SELECT, use PERFORM instead.
            CONTEXT:  PL/pgSQL function "checksold" line 2 at SQL statement

What is wrong with the trigger. Without the trigger it works great.

Thank you for you help.

+2  A: 

Replace

SELECT offer_id FROM offer WHERE offer_id = NEW.offer_id AND date_sale IS NULL;

with

PERFORM offer_id FROM offer WHERE offer_id = NEW.offer_id AND date_sale IS NULL;

as suggested.

More info in the manual ("38.5.2. Executing a Command With No Result").

Milen A. Radev
Thank you this works :-)
ThreeFingerMark