Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising error in postgreSQL

CREATE OR REPLACE FUNCTION msgfailerror() RETURNS trigger AS 
' BEGIN 
    IF NEW.noces< new.first_column THEN 
        RAISE EXCEPTION 'cannot have a negative salary'; 
    END IF; 
   return new; 
END' LANGUAGE plpgsql

Trigger

create trigger msgfail before insert on first for each row 
execute procedure msgfailerror()

Giving error:

syntax error at or near "cannot" LINE 5: RAISE EXCEPTION 'cannot have a negative ...

I have almost one validation for each field of row. I want trigger to check all validations while insertion is being done and, raise error log afterwards once for all. Should I use raise exception on raise notice ?

For example:

Insert into first (first_column, noces,dob) values ('4545','75','545') 

I am checking noces is less than first_column, for the same row i want to check if dob > 80 and if first_column is integer and raise error for all validations. Thanks in advance

like image 677
user1686308 Avatar asked Sep 21 '12 10:09

user1686308


People also ask

What is raise exception in PostgreSQL?

RAISE EXCEPTION in PostgreSQL is basically used to raise the warning and error message. It is very useful and important. There are six levels of raise exception is available in PostgreSQL, i.e. notice, log, debug, warning info and exception. It is used in various parameters.

How do you handle user defined exceptions in PostgreSQL?

locate 'EXCEPTION' keyword, find out if it is an user defined or standard exception. if it is an user defined exception, delete the corresponding declaration and specify unique error code via ERRCODE in a USING clause. in catch-block replace SQLCODE by SQLSTATE.


1 Answers

The quoting is wrong. It's easier to use dollar quotes $$:

CREATE OR REPLACE FUNCTION msgfailerror() 
RETURNS trigger AS 
$$
BEGIN 
  IF NEW.noces< new.first_column THEN 
    RAISE EXCEPTION 'cannot have a negative salary'; 
  END IF; 
  return new; 
END;
$$
LANGUAGE plpgsql;

But on the other hand, what's wrong with a check constraint?

like image 63
Frank Heikens Avatar answered Oct 28 '22 07:10

Frank Heikens