Problem creating Stored Procedure in MySQL - 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 ;

Related

ERROR 1064 in mysql, can anybody check what is the error?

CREATE PROCEDURE insert_user(in uname varchar(20),in gender varchar(20),in email varchar(20),in phone varchar(20),in pword varchar(20),in city varchar(20))
BEGIN
DECLARE finished integer default 0;
Declare cnt integer default 0;
declare id integer;
DECLARE c_cur cursor for select user_id from user;
DECLARE CONTINUE HANDLE FOR NOT FOUND SET finished = 1;
open c_cur;
ins_user: loop
fetch c_cur into id;
IF finished = 1 THEN
LEAVE ins_user;
end if;
cnt:=id;
end loop ins_user;
cnt:=cnt+1;
insert into user
values(cnt,uname,email,phone,city,pword,gender);
END;
Am getting the error #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'HANDLE FOR NOT FOUND SET finished = 1; open c_cur; ins_user: loop fetch ' at line 7
i am not sure where its getting wrong
Set the Delimiter to something else, other than ;, for eg: $$. This will allow the parser to treat the whole create statement as one.
At the end, redefine the Delimiter back to ;
user is a keyword in MySQL. It is better to rename your table to something else, or use backticks around it.
There is a typo; it should be HANDLER not HANDLE
Try:
DELIMITER $$
DROP PROCEDURE IF EXISTS insert_user $$
CREATE PROCEDURE insert_user(in uname varchar(20),
in gender varchar(20),
in email varchar(20),
in phone varchar(20),
in pword varchar(20),
in city varchar(20))
BEGIN
DECLARE finished INT DEFAULT 0;
Declare cnt INT DEFAULT 0;
declare id INT;
DECLARE c_cur CURSOR FOR select user_id from `user`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
open c_cur;
ins_user: loop
fetch c_cur into id;
IF finished = 1 THEN
LEAVE ins_user;
end if;
SET cnt:=id; -- set was missing here
end loop ins_user;
SET cnt:=cnt+1; -- set was missing here
insert into `user`
values(cnt,uname,email,phone,city,pword,gender);
END $$
DELIMITER ;

Mysterious error in CREATE PROCEDURE in MariaDB/MySQL

I tried to make a simple procedure in MariaDB 10.2 but I encountered an issue regarding variables defining.
I am receiving (conn:107) 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 3 message when I declare a variable.
I read the MariaDB documentation and I it says that a variable is defined like this DECLARE var_name [, var_name] ... type [DEFAULT value]
Where I am wrong? I am coming from Oracle SQL and some sintax is wired for me.
I use Eclipse with MariaDB JDBC to connect on SQL.
CREATE PROCEDURE nom_jobs_insert(IN p_name varchar(100) CHARACTER SET 'utf8')
BEGIN
DECLARE counter INT DEFAULT 0;
SELECT count(*) INTO counter
FROM nom_jobs
WHERE lower(name) = lower(p_name)
IF counter = 1 THEN
INSERT INTO nom_jobs(name) VALUES (p_name);
END IF;
END;
I found the solution.
In MariaDB you have to define a delimiter before create a procedure and you need to mark where the procedure code is finished.
DELIMITER //
CREATE PROCEDURE nom_jobs_insert(IN p_name varchar(100) CHARACTER SET 'utf8')
BEGIN
DECLARE counter INT DEFAULT 0;
SELECT count(*) INTO counter
FROM nom_jobs
WHERE lower(name) = lower(p_name);
IF counter = 1 THEN
INSERT INTO nom_jobs(name) VALUES (p_name);
END IF;
END; //
You have error not in DECLARE expression, add ; after SELECT statement
Here are the clues that point to a missing DELIMITER:
near '' at line 3
Line 3 contains the first ;
When the error says near '', the parser thinks it has run off the end of the "statement".
Put those together -- it thinks that there is one 3-line statement ending with ;. But the CREATE PROCEDURE should be longer than that.
CREATE PROCEDURE nom_jobs_insert(IN p_name varchar(100) CHARACTER SET 'utf8')
IS
DECLARE counter INTEGER DEFAULT 0;
BEGIN
SELECT count(*) INTO counter
FROM nom_jobs
WHERE lower(name) = lower(p_name)
IF counter = 1 THEN
INSERT INTO nom_jobs(name) VALUES (p_name);
END IF;
END;

MySQL stored Proc syntax confusion

Using syntax form docs, read many examples and docs, I have reduced code down to isolate the syntax that is causing the failure, I cannot see it... I'm still getting an error.
Running thru MySQL command line
PARAMS: A_score smallint, B_score smallint
delimiter $$
create procedure my_procedure(A_score smallint, B_score smallint)
begin
DECLARE winner BIGINT DEFAULT 0;
DECLARE winningScore, losingScore SMALLINT DEFAULT;
if A_score > B_score then
SET winningScore = 1;
elseif A_score < B_score then
SET winningScore = 2;
end if;
start transaction;
UPDATE
winners
SET
winner = winningScore
WHERE
id = 1
commit;
end $$
delimiter ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near ';
if A_score > B_score then
SET winningScore = 1;
elseif A_score' at line 4
I see you forgot to write SET (in the previous version of your question) to assign values to your variables.
(I changed the type for winningScore and losingScore to be characters, because smallints can't be strings):
-- Be sure to change the default delimiter before writing your procedure
delimiter $$
create procedure my_procedure(A_score smallint, B_score smallint)
begin
DECLARE winner BIGINT DEFAULT 0;
DECLARE winningScore, losingScore VARCHAR(2) DEFAULT;
if A_score > B_score then
SET winningScore = 'A';
-- ^^^--you forgot this
elseif A_score < B_score then
SET winningScore = 'B';
-- ^^^--and this
else
SET winningScore = 'AB';
-- ^^^--and this
end if;
start transaction;
-- Do whatever your transaction is meant to be
commit;
end $$
-- ^^--- And I think you're forgetting to put this
-- Be sure to reset the delimiter to ; after you end your procedure
delimiter ;
Quoting from the reference manual:
Variables can be set directly with the SET statement. See Section 13.7.4, “SET Syntax”.
Hope this helps

Create MySQL function statement

I've written a function but it gives me mistake a the second line (create statement) if anyone could help me, I really appreciate:
CREATE FUNCTION GetPrefix (phone_num VARCHAR(30)) RETURNS varchar(30)
deterministic
BEGIN
DECLARE x INT;
DECLARE prefix varchar(30);
SET x = 0;
for prefix in SELECT code
FROM tab_len
while (length(phone_num)) > 0
do
if prefix<>left(phone_num, length(phone_num)-x)
then set x=x+1 ;
else return 1 ;
END while ;
END $$;
and I receive this error :
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'for prefix in SELECT code
FROM tab_len while (length(phone_n' at line 9
DELIMITER $$
DROP FUNCTION IF EXISTS GetPrefix $$
CREATE FUNCTION GetPrefix
(
phone_num VARCHAR(30)
)
RETURNS varchar(30)
BEGIN
DECLARE var_x INT DEFAULT 0;
DECLARE var_prefix VARCHAR(100);
SET phone_num = IFNULL(phone_num,'');
-- your logic will go here.
return phone_num;
END$$
DELIMITER ;
SELECT GetPrefix('test');
This is right syntax to write a function in mysql.
check out the differences. Take a look Here

Get result occur from update statement inside stored procedures

I want to check the existance of specific record in db table, if it's exist then update if not I want to add new record
I am using stored procedures to do so, First I make update stetement and want to check if it occurs and return 0 then there's no record affected by update statement and that means the record does not exist.
I make like this
DELIMITER //
CREATE PROCEDURE revokePrivilegeFromUsers(IN userId int(11), IN privilegeId int(11), IN deletedBy int(11))
BEGIN
DECLARE isExist int;
isExist = update `user_privileges` set `mode` ='d' ,`updated_by` = deletedBy, `date_time_assigned` = CURRENT_TIMESTAMP() where `user_id`= userId and `privilege_id`=privilegeId;
IF isExist == 0 THEN
insert into `user_privileges`(`user_id`,`privilege_id`,`mode`,`date_time_assigned`,`updated_by`)values (userId ,privilegeId ,'d',CURRENT_TIMESTAMP(),deletedBy );
END IF;
END //
DELIMITER ;
This error occur with me
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= update `user_privileges` set `mode` ='d' ,`updated_by` = deletedBy, `date_time' at line 6
Is the way I am working is supported by mysql?
I solve the problem, I had 2 prblems
ROW_COUNT() is used to get the number of rows affected in insert, update or delete statements.
Equals comparison in stored procedure is = not ==
The correct stored procedure is
DELIMITER //
CREATE PROCEDURE revokePrivilegeFromUsers(IN userId int(11), IN privilegeId int(11), IN deletedBy int(11))
BEGIN
DECLARE count int default -1;
update `user_privileges` set `mode` ='d' ,`updated_by` = deletedBy, `date_time_assigned` = CURRENT_TIMESTAMP() where `user_id`= userId and `privilege_id`=privilegeId;
SELECT ROW_COUNT() into count ;
IF count = 0 THEN
insert into `user_privileges`(`user_id`,`privilege_id`,`mode`,`date_time_assigned`,`updated_by`)values (userId ,privilegeId ,'d',CURRENT_TIMESTAMP(),deletedBy );
END IF;
END //
DELIMITER ;
Use the INSERT IGNORE statement instead. I assume that your table has (user_id, privilege_id) as a unique key.
insert ignore into user_privileges (user_id,privilege_id,`mode,date_time_assigned,updated_by)
values (userId ,privilegeId ,'d',CURRENT_TIMESTAMP(),deletedBy )
on duplicate key update mode='d', date_time_assigned=now(),updated_by=deletedBy