how to create Trigger in postgresql for checking function exit or not
I m new to postgresql and database part. I want to c开发者_如何学Check function exit or not in postgresql using trigger before insert statement. any body know how to create trigger this?
Create a special trigger function:
CREATE OR REPLACE FUNCTION some_function()
RETURNS trigger AS $$
BEGIN
IF some_condition THEN
RAISE EXCEPTION 'Some message for id %', NEW.id;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
Then define a trigger to fire it
CREATE TRIGGER some_trigger
BEFORE INSERT OR UPDATE ON some_table
FOR EACH ROW EXECUTE PROCEDURE some_function();
When the exception is raised, the update will fail.
The SQL executed may be or arbitrary complexity, involving any query or function you like. It may also change the NEW values via SET NEW.some_column = some_value
, or even update other tables.
Note the NEW.id
is an example column only. Use whatever column you like from the NEW row (or none) in the message.
If the check is localized to the row, consider using a column constraint, eg:
CREATE TABLE my_table (
some_column int CHECK (some_column between 0 and 10),
other_column int CHECK (other_column < some_column)
)
精彩评论