简体   繁体   中英

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

  • 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 ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM