重复条目Mysql主要

时间:2013-06-27 10:33:09

标签: mysql database stored-procedures

在此代码中出现错误, 试图调试但找不到答案。

有人可以纠正我吗?

BEGIN

DECLARE FINALID VARCHAR(8);
DECLARE MAXIDCOMPANY VARCHAR(8);

        SELECT MAX(SUBSTRING(company.idCompany,3,8))+1 INTO MAXIDCOMPANY 
        FROM company 
        WHERE SUBSTRING(company.idCompany,1,2) = SUBSTRING(nmCompany,1,2);


                IF MAXIDCOMPANY > 0 AND MAXIDCOMPANY < 10 THEN
                    SET FINALID = CONCAT(SUBSTRING(nmCompany,1,2),'00', CONVERT(MAXIDCOMPANY USING latin1));
                    ELSEIF MAXIDCOMPANY > 9 AND MAXIDCOMPANY < 100 THEN
                        SET FINALID = CONCAT(SUBSTRING(nmCompany,1,2),'0', CONVERT(MAXIDCOMPANY USING latin1));
                            ELSEIF MAXIDCOMPANY > 99  THEN
                            SET FINALID = CONCAT(SUBSTRING(nmCompany,1,2), CONVERT(MAXIDCOMPANY USING latin1));
                END IF;

                        IF MAXIDCOMPANY IS NULL THEN
                            SET FINALID = CONCAT(SUBSTRING(nmCompany,1,2),'001');
                        END IF;

                INSERT INTO company
                (company.idCompany, company.nmCompany, company.country, company.address, company.region, company.joinDate, company.quota, company.createdUser, company.createdDate, company.updatedUser, company.updatedDate)
                VALUES
                (FINALID, nmCompany, country, address, region, joinDate, quota, createdUser, NOW(), updatedUser, updatedDate);



END

那是代码,程序在1000之后坚持到了计数器。

示例:

当我将例如IN1000的数据添加为idCompany时,它总是卡在该数字上,但当我查询最大数据时它只显示IN999,为什么不显示IN1000

非常感谢

1 个答案:

答案 0 :(得分:0)

因为函数max与SUB-STRING结合将返回变量字符内的最大值,并且解决方法是用count函数替换它,逻辑计数将返回最大值。

SELECT COUNT(company.idCompany) + 1 INTO MAXIDCOMPANY from company where SUBSTRING(company.idCompany,1,2) = SUBSTRING(company.idCompany,1,2);

基于我的商业散文,谢谢大家的答案..