Search code examples
mysqlstored-proceduresmysql-error-1064

Problem creating Stored Procedure in MySQL


I have written the below mentioned script in MySQL to create Stored Procedure:

CREATE PROCEDURE `AddBranch`(
IN `inCompanyCode` char(3), 
IN `inBranchCode` varchar(6), 
IN `inBankBranch` varchar(40)
)
BEGIN
    DECLARE branchExists TINYINT DEFAULT 0;
    SELECT Count(*) INTO branchExists FROM branches WHERE CompanyCode = inCompanyCode AND BranchCode = inBranchCode;
    IF branchExists = 0 THEN
        INSERT INTO branches VALUES (inCompanyCode, inBranchCode, inBankBranch);
    ELSE
        UPDATE branches SET Branch = inBankBranch
        WHERE CompanyCode = inCompanyCode AND BranchCode = inBranchCode;
    END IF;
END;

While running the query, the error message displayed is:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 7

I have even tried DECLARE branchExists TINYINT(1) DEFAULT 0; but the problem persists.

What is wrong with line 7?

Regards


Solution

    • You need to redefine Delimiter to something else (eg: $$), instead of (;).
    • Also as a safety measure, check if the same name procedure already exists or not (DROP PROCEDURE IF EXISTS)
    • At the end, redefine the DELIMITER to ;

    Change the stored procedure to as follows:

    DELIMITER $$
    DROP PROCEDURE IF EXISTS `AddBranch`$$
    
    CREATE PROCEDURE `AddBranch`(
    IN `inCompanyCode` char(3), 
    IN `inBranchCode` varchar(6), 
    IN `inBankBranch` varchar(40)
    )
    BEGIN
        DECLARE branchExists TINYINT DEFAULT 0;
        SELECT Count(*) INTO branchExists FROM branches WHERE CompanyCode = inCompanyCode AND BranchCode = inBranchCode;
        IF branchExists = 0 THEN
            INSERT INTO branches VALUES (inCompanyCode, inBranchCode, inBankBranch);
        ELSE
            UPDATE branches SET Branch = inBankBranch
            WHERE CompanyCode = inCompanyCode AND BranchCode = inBranchCode;
        END IF;
    END$$
    
    DELIMITER ;