[MySQL] Función para generar id de producto

DELIMITER $$ USE `table`$$ CREATE DEFINER=`user`@`host` FUNCTION `id_producto`(cat INT, prov INT) RETURNS VARCHAR(8) CHARSET utf8 BEGIN DECLARE id_aux INT; DECLARE id VARCHAR(4); DECLARE id_prod VARCHAR(12); SET id_aux = (SELECT COUNT(*) FROM productos); IF id_aux = 0 THEN SET id = '0001'; ELSE IF id_aux > 0 AND id_aux < 8 THEN SET id = CONCAT('000',id_aux + 1); ELSEIF id_aux > 9 AND id_aux <98 THEN SET id = CONCAT('00',id_aux + 1); ELSEIF id_aux > 99 AND id_aux <998 THEN SET id = CONCAT('0',id_aux + 1); ELSEIF id_aux > 999 THEN SET id = id_aux + 1; END IF; END IF; SET id_prod = CONCAT(cat,prov,id); RETURN id_prod; END$$ DELIMITER ;
Generar id de producto (8 caracteres). Estructura id: id_categoria_producto(2 caracteres) + id_proveedor_producto(2 caracteres) + numero_producto(4 caracteres) , ejemplo: 11 11 0001.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.