MySQL VARCHAR,如具有MIN和MAX字符长度的数据类型 [英] MySQL VARCHAR like Data type with MIN and MAX character lengths

查看:317
本文介绍了MySQL VARCHAR,如具有MIN和MAX字符长度的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要查找与我想要的值类似的VARCHAR数据类型,但是有没有办法设置MIN/MAX字符长度?

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 character length?

VARCHAR(6,10)

这将至少包含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 ;;

虽然SIGNAL不可用,但调用未定义的存储过程就足够了(在本例中为col_length_outside_range_error).否则,我认为使用数据库的应用程序将需要进行检查.

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.

这篇关于MySQL VARCHAR,如具有MIN和MAX字符长度的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆