mysql varchar min,MySQL VARCHAR,如具有MIN和MAX字符长度的数据类型

本文介绍如何使用MySQL存储过程创建一个触发器,确保VARCHAR类型的字段值在预设的最小(6)和最大(10)字符长度范围内。通过触发器机制,当插入的数据超出范围时会抛出错误,减轻应用层面的校验负担。
摘要由CSDN通过智能技术生成

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)

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值