Raising error in postgreSQL

前端 未结 3 1193
無奈伤痛
無奈伤痛 2021-02-20 03:45
CREATE OR REPLACE FUNCTION msgfailerror() RETURNS trigger AS 
\' BEGIN 
    IF NEW.noces< new.first_column THEN 
        RAISE EXCEPTION \'cannot have a negative sala         


        
相关标签:
3条回答
  • 2021-02-20 03:59

    there is nothing wrong with you the only thing is using quotes

    please change :

    RAISE EXCEPTION 'cannot have a negative salary';
    

    to:

    RAISE EXCEPTION ''cannot have a negative salary'';
    

    '' is different from "

    '' = two single quotes

    0 讨论(0)
  • 2021-02-20 04:09

    I agree with Frank that you could better use constraints, but you call it validation. Validation is typically done before insertion takes place. If you would like to validate insertions, you could use functions instead of triggers or constraints.

    When you would write functions is the answer to your question to raise exceptions or notices that as long as there has been no write action a notice would suffice (together with leaving the function). Once there has been a write to the database, do you have to use exceptions as they perform a rollback.

    Like this:

    CREATE OR REPLACE FUNCTION field_validate(p_int int) RETURNS boolean AS $$
    
    DECLARE
     i_id int;
    BEGIN 
      if p_int > 10 then
       raise notice 'should be smaller then 10';
       return false;
      end if;
      insert into tbl_numbers(firstfield) values(p_int) returning id in i_id;
      insert into tbl_fake(nofield) values(i_id);
      return true;
    EXCEPTION
      WHEN raise exception THEN
       return false;
    END;
    $$ LANGUAGE plpgsql;
    
    0 讨论(0)
  • 2021-02-20 04:14

    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?

    0 讨论(0)
提交回复
热议问题