在 MySQL 中创建存储过程时出现问题

Problem creating Stored Procedure in MySQL

我在 MySQL 中编写了下面提到的脚本来创建存储过程:

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;

在运行查询时,显示的错误信息是:

1064 - 您的 SQL 语法有误;查看与您的 MariaDB 服务器版本对应的手册,了解在第 7 行

附近使用的正确语法

我什至尝试过 DECLARE branchExists TINYINT(1) DEFAULT 0; 但问题仍然存在。

第 7 行有什么问题?

此致

  • 您需要将 Delimiter 重新定义为其他内容(例如:$$),而不是 (;).
  • 同时作为安全措施,检查是否已经存在同名程序(DROP PROCEDURE IF EXISTS)
  • 最后,将DELIMITER重新定义为;

将存储过程改成如下:

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 ;