'Mysql exists operator not working correctly or there is any other problem?

I have two tables

  • txn_maxvoucherno (companycode, dbcode, vouchertype, fyear, series, voucherno)
  • txn_vouchersdetails (voucherno, vouchertype)

I am executing a stored procedure to generate new voucher no in txn_maxvoucherno table, which is max(voucherno)+1, then I check in txn_vouchersdetails for an entry to exists in this table if it exists it will again increment the voucherno by 1 and check again. This happens three times. so there three attempts to find voucherno every time by incrementing one before throwing an error.

The problem is it always go inside first if condition even if the voucher no does not exists in the table or exists in the table.

This is the stored procedure:

CREATE DEFINER=`root`@`localhost` PROCEDURE `spGenerateVoucherNo`(in companyCode int, IN dbCode int, in vouType nvarchar(10), IN Fyear int, IN series int, IN VoucherNo int, OUT NewVoucherNo INT)
BEGIN
    SELECT MAX(VoucherNo) INTO NewVoucherNo from txn_maxvoucherno
    WHERE CompanyCode = companyCode AND DBCode = dbCode AND VoucherType = vouType
    GROUP BY VoucherType;
    IF EXISTS (SELECT 1 from txn_vouchersdetails WHERE VoucherNo = NewVoucherNo AND VoucherType like vouType) then
    BEGIN
        SET NewVoucherNo = NewVoucherNo + 1;
        IF EXISTS (SELECT 1 from txn_vouchersdetails WHERE VoucherNo = NewVoucherNo AND VoucherType like vouType) then
        BEGIN
            SET NewVoucherNo = NewVoucherNo + 1;
            IF EXISTS (SELECT 1 from txn_vouchersdetails WHERE VoucherNo = NewVoucherNo AND VoucherType like vouType) then
            BEGIN
                /* Return Error */
                SET NewVoucherNo = -1;
                SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Issue on server. Please try after some time.';
            END;
            END IF;
        END;
        END IF;
    END;
    END IF;
END

The table data are as below txn_maxvoucherno:

companyCode DBCode  VoucherType FYear   Series  VoucherNo

1   1   SAL 2022    1   1

txn_vouchersdetails:

VoucherNo   VoucherType

1   SAL
2   SAL
3   SAL


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source