1

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

1 Answer 1

1
  • 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 ;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked. But could you please tell me why do we need $$?
@kush.impetus $$ is just an example. It could be anything like ??. To create a stored procedure, we have to run the above query. And, we want this whole statement to get stored as a SP, together. But, if we have ; in between, MySQL parser will try to execute statements individually, which wont make any sense (instead of storing it as a SP). So, we set the delimiter to something else, so that it gets stored properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.