set maximum value to a column

后端 未结 3 537
梦如初夏
梦如初夏 2021-01-18 01:08

I have a table with a column (int type) called age. This column should hold maximun value 50. If it exceeds then it shouldn\'t update that row.

Means this column sho

相关标签:
3条回答
  • 2021-01-18 01:40

    Try this:

    CREATE TRIGGER check_trigger
      BEFORE INSERT
      ON table
      FOR EACH ROW
    BEGIN
      IF NEW.age<0 OR NEW.age>50 THEN
        CALL `Error: Wrong values for age`; -- this trick will throw an error
      END IF;
    END
    
    0 讨论(0)
  • 2021-01-18 01:48

    You could use CHECK constraint:

    CREATE TABLE person (
    Name VARCHAR(80), 
    Age  INT CHECK (Age BETWEEN 5 and 50));
    
    0 讨论(0)
  • 2021-01-18 01:52
    create table test (
    age tinyint not null ) engine = myisam;
    
    delimiter //
    drop trigger if exists max_num//
    create trigger max_num before insert on test
    for each row 
    begin
    if new.age < 0 or new.age > 50 then
    set new.age = null;
    end if;
    end//
    delimiter ;
    
    insert into test (age) values (100);
    

    Make the same thing for update.

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