开发者

MySQL VARCHAR like Data type with MIN and MAX character lengths

开发者 https://www.devze.com 2022-12-30 12:25 出处:网络
Looking for a data type that is similar to VARCHAR as to the values I would like, but is there a way to have a MIN/MAX char开发者_如何学Pythonacter length?

Looking for a data type that is similar to VARCHAR as to the values I would like, but is there a way to have a MIN/MAX char开发者_如何学Pythonacter length?

VARCHAR(6,10)

This would have a minimum of 6 characters and a maximum of 10 characters.


You could add a trigger to throw an exception when the values are outside of the range, e.g.

DELIMITER $$

CREATE TRIGGER `insert_table_var` BEFORE INSERT ON `table` 
FOR EACH ROW
BEGIN
     DECLARE str_len INT DEFAULT 0;
     DECLARE max_len INT DEFAULT 10;
     DECLARE min_len INT DEFAULT 6;

     SET str_len = LENGTH(NEW.col);

     IF str_len > max_len OR str_len < min_len 
     THEN
           CALL col_length_outside_range_error();
     END IF;
END $$
DELIMITER ;;

Whilst SIGNAL is not available, calling an undefined stored procedure would suffice (in this case col_length_outside_range_error). Otherwise, I think that the application using the database is going to need to do the checks.


This is called CHECK constraint in SQL and it is ignored by MySQL.

The CHECK clause is parsed but ignored by all storage engines.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号