MySQL INSERT IF condition is true - mysql

I'm making a stored routine in MySQL, and I would like to know whether it is possible to make an INSERT-IF some condition is TRUE, ELSE INSERT something else.
This is My Query but I keep getting the #1064 Error (SQL Syntax Error).
DECLARE a INT;
DECLARE b INT;
DECLARE changeTypeID INT DEFAULT(0);
SET a = (SELECT roomPrice FROM RPH WHERE tier=1 AND
startDate = '2018-02-20' AND rTypeID=1);
SET b = (SELECT roomPrice FROM RPH WHERE tier=1 AND
startDate = '2018-02-20' AND rTypeID=2);
SET changeTypeID = CASE WHEN (a>b) THEN 1 WHEN (a<b) THEN 2 WHEN a=b THEN 3 END;
IF (changeTypeID = 1 OR changeTypeID =2) THEN
(
INSERT INTO TABLE_A (X,Y,Z) VALUES (ID, changeTypeID, createdBy);
)
ELSEIF (changeTypeID = 3) THEN
(
INSERT INTO TABLE_B (P,Q,R) VALUES (ID, rID, createdBy);
)
END IF;
Here is the error message:
SQL Error (1064): You have an error in your SQL Syntax; check the manual
that corresponds to your MySQL version for the right syntax to use near
'INSERT INTO TABLE_A (X,Y,Z)' at line 19
Note: The insert parameter is already declared on the routine beforehand.
Any help will be appreciated :)

DECLARE a INT;
DECLARE b INT;
DECLARE changeTypeID INT DEFAULT(0);
SET a = (SELECT roomPrice FROM RPH WHERE tier=1 AND
startDate = '2018-02-20' AND rTypeID=1);
SET b = (SELECT roomPrice FROM RPH WHERE tier=1 AND
startDate = '2018-02-20' AND rTypeID=2);
SET changeTypeID = CASE WHEN (a>b) THEN 1 WHEN (a<b) THEN 2 WHEN a=b THEN 3 END;
IF (changeTypeID = 1 OR changeTypeID =2) THEN
INSERT INTO TABLE_A (X,Y,Z) VALUES (ID, changeTypeID, createdBy);
ELSEIF (changeTypeID = 3) THEN
INSERT INTO TABLE_B (P,Q,R) VALUES (ID, rID, createdBy);
END IF;

Related

Stored procedure returns ER_BAD_NULL_ERROR

On MySql 5.7, I'd like to run this procedure which is supposed to fetch tag1 of articles from article table and insert them into article_tag table:
DELIMITER $$
CREATE PROCEDURE dt1()
BEGIN
DECLARE maxid INT;
DECLARE x INT;
DECLARE tag1 VARCHAR(30);
DECLARE ntag1 int;
SET maxid = (SELECT MAX(id) FROM `article`);
SET x = (SELECT MIN(id) FROM ` article`) ;
WHILE x<= maxid DO
SET tag1 = (SELECT tag1 from `article` WHERE id=x);
call debug_msg(TRUE, tag1);
SET ntag1 = (SELECT count(*) from `article_tag` WHERE tag=tag1);
IF ntag1 = 0 THEN INSERT INTO `article_tag` (tag, slug, frequency) VALUES (tag1, tag1, 1);
ELSE UPDATE ` article_tag` SET frequency = frequency + 1 WHERE tag=tag1 ;
END IF;
SET x = x + 1;
END WHILE;
END$$
I can confirm than none of the tag1 values is null:
SELECT count(*) from `article` WHERE tag1 IS NULL;
+----------+
| count(*) |
+----------+
| 0 |
+----------+
However when I run the procedure, I get:
ERROR 1048 (23000): Column 'tag' cannot be null
Here is a reproducible example.
https://www.db-fiddle.com/f/3ymPtabSksRUMSBep7SyX8/5
This problem bugs me for hours. So appreciate on hints on why this happens, and how to fix it?

#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

I keep getting this error when trying to Run SQL query/queries on database weeki. I searched everywhere for a solution but I was just unlucky.
#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 '' at line 5
I am trying to add this to my databases
CREATE FUNCTION weeki.CreateGroup(GroupName VARCHAR(50), GroupIcon TEXT, GroupDescription VARCHAR(130), GroupCreator INT)
RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE groupID INT;
INSERT INTO groups (name, icon, description) VALUES (GroupName, GroupIcon, GroupDescription);
SET groupID = LAST_INSERT_ID();
INSERT INTO group_members VALUES (groupID, GroupCreator);
RETURN groupID;
END;
CREATE FUNCTION weeki.AddMessage(r VARCHAR(255), s INT, t INT, m VARCHAR(255), creation DATETIME)
RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE lastID INT;
DECLARE receiver INT;
SELECT id INTO receiver from users WHERE username=r;
INSERT INTO messages (receiver_id, sender_id, msg_type, message, created_At) values(receiver, s, t, m, creation);
SET lastID = LAST_INSERT_ID();
INSERT INTO messages_receipt (message_id, user_id, is_delivered) VALUES (lastID, receiver, 0);
RETURN lastID;
END;
CREATE FUNCTION weeki.AddGroupMessage(gid INT, s INT, t INT, m VARCHAR(255), creation DATETIME)
RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE lastID INT; DECLARE rowCount INT;
SELECT COUNT(*) INTO rowCount FROM group_members WHERE user_id = s AND group_id = gid;
IF rowCount = 1 THEN
INSERT INTO group_messages (group_id, user_id, msg_type, message, created_at) VALUES (gid, s, t, m, creation);
SET lastID = LAST_INSERT_ID();
INSERT INTO group_receipt (message_id, user_id, is_delivered) SELECT gm.message_id, gmembers.user_id, 0 FROM
group_messages gm LEFT JOIN group_members gmembers ON gmembers.group_id = gm.group_id WHERE gm.group_id = gid AND gm.message_id = lastID AND NOT gmembers.user_id = s;
RETURN lastID;
ELSE
return 0;
END IF;
END;
CREATE DEFINER = 'abdal'#'localhost'
FUNCTION weeki.AddGroupMember(GroupID INT, MemberName VARCHAR(255), Username INT)
RETURNS int(11)
BEGIN
INSERT INTO group_members VALUES (GroupID, MemberName);
RETURN 1;
END;
Anyone have any ideas on how to fix this? I appreciate all the answers.
What #GordonLinoff said!
DELIMITER ##
CREATE FUNCTION weeki.CreateGroup(GroupName VARCHAR(50), GroupIcon TEXT, GroupDescription VARCHAR(130), GroupCreator INT)
RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE groupID INT;
INSERT INTO groups (name, icon, description) VALUES (GroupName, GroupIcon, GroupDescription);
SET groupID = LAST_INSERT_ID();
INSERT INTO group_members VALUES (groupID, GroupCreator);
RETURN groupID;
END##
CREATE FUNCTION weeki.AddMessage(r VARCHAR(255), s INT, t INT, m VARCHAR(255), creation DATETIME)
RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE lastID INT;
DECLARE receiver INT;
SELECT id INTO receiver from users WHERE username=r;
INSERT INTO messages (receiver_id, sender_id, msg_type, message, created_At) values(receiver, s, t, m, creation);
SET lastID = LAST_INSERT_ID();
INSERT INTO messages_receipt (message_id, user_id, is_delivered) VALUES (lastID, receiver, 0);
RETURN lastID;
END##
CREATE FUNCTION weeki.AddGroupMessage(gid INT, s INT, t INT, m VARCHAR(255), creation DATETIME)
RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE lastID INT; DECLARE rowCount INT;
SELECT COUNT(*) INTO rowCount FROM group_members WHERE user_id = s AND group_id = gid;
IF rowCount = 1 THEN
INSERT INTO group_messages (group_id, user_id, msg_type, message, created_at) VALUES (gid, s, t, m, creation);
SET lastID = LAST_INSERT_ID();
INSERT INTO group_receipt (message_id, user_id, is_delivered) SELECT gm.message_id, gmembers.user_id, 0 FROM
group_messages gm LEFT JOIN group_members gmembers ON gmembers.group_id = gm.group_id WHERE gm.group_id = gid AND gm.message_id = lastID AND NOT gmembers.user_id = s;
RETURN lastID;
ELSE
return 0;
END IF;
END##
CREATE DEFINER = 'abdal'#'localhost'
FUNCTION weeki.AddGroupMember(GroupID INT, MemberName VARCHAR(255), Username INT)
RETURNS int(11)
BEGIN
INSERT INTO group_members VALUES (GroupID, MemberName);
RETURN 1;
END##
DELIMITER ;

Storing MySQL query as function

I'm new to MySQL functions. I Created a function:
CREATE FUNCTION `tems`.`<function_name>`(IN bid INT, IN cid INT)
RETURNS INT(10)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE min_no INT;
SELECT COALESCE(min(number),1)
FROM
(SELECT r1.number -1 AS number, r1.branch_id, r1.course_id
FROM `Room` AS r1
LEFT JOIN `Room` AS r2
ON r1.branch_id = r2.branch_id
AND r1.course_id = r2.course_id
AND (r1.number - 1) = r2.number
WHERE r1.number > 1 AND r2.number IS NULL
UNION ALL
SELECT max(number) + 1, branch_id, course_id
FROM `Room`
GROUP BY branch_id, course_id) AS q
WHERE branch_id=bid AND course_id=cid
GROUP BY branch_id, course_id
INTO min_no;
RETURN (min_no);
END;
And I want to get bid, cid and return the select value, but I'm getting an error message:
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 'IN bid INT, IN cid INT)
RETURNS INT(10)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS ' at line 1
What am I doing wrong?
Use a DELIMITER like below along with removing the two part identifier. Just declare the function name.
DELIMITER $$
CREATE FUNCTION MyTestFunc (bid INT, cid INT)
RETURNS INT(10)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE min_no INT;
SELECT COALESCE(min(number),1)
FROM
(SELECT r1.number -1 AS number, r1.branch_id, r1.course_id
FROM `Room` AS r1
LEFT JOIN `Room` AS r2
ON r1.branch_id = r2.branch_id
AND r1.course_id = r2.course_id
AND (r1.number - 1) = r2.number
WHERE r1.number > 1 AND r2.number IS NULL
UNION ALL
SELECT max(number) + 1, branch_id, course_id
FROM `Room`
GROUP BY branch_id, course_id) AS q
WHERE branch_id=bid AND course_id=cid
GROUP BY branch_id, course_id
INTO min_no;
RETURN (min_no);
END$$
DELIMITER ;

In MySQL stored procedure getting output 1 in count and if I am executing only query then I am getting output 0

SELECT COUNT(id) INTO student_count FROM student_info WHERE roll_no=roll_no and division_id = division_id and institute_id=institute_id and academic_year_id = academic_year;
I am getting student_count = 1
when I am trying to execute stored procedure.
When I am executing direct query as below:
SELECT COUNT(*) AS c FROM student_info WHERE division_id=9 AND institute_id=1 and academic_year_id =11 and roll_no='12617690';
I am getting result 0 which is right. My procedure is:
**CREATE DEFINER = 'root'#'localhost'
PROCEDURE smart_school.create_student(IN academic_year int(11),IN standard_id int(11),IN division_id int(11),IN student_user_id int(11),IN gr_no VARCHAR(20),IN roll_no VARCHAR(50),IN institute_id INT(11),IN maker_id INT(11),OUT create_student_result varchar(20))
BEGIN
DECLARE student_id int;
DECLARE student_count int;
DECLARE semester varchar(10);
DECLARE exit handler for sqlexception
BEGIN
SET create_student_result = "failure";
SELECT #create_student_result;
ROLLBACK;
END;
IF NOT EXISTS (select id from role_user where user_id = student_user_id and role_id = 3 and institute_id=institute_id limit 0,1) THEN
BEGIN
select COUNT(id) INTO student_count from student_info WHERE roll_no=roll_no and division_id = division_id and institute_id=institute_id and academic_year_id = academic_year;
if student_count < 1 then
BEGIN
START TRANSACTION;
insert into student (is_active,user_id,maker_id,caste_id,category_id,created_at,updated_at) values ('1',student_user_id,maker_id,1,1,NOW(),NOW());
SET student_id = LAST_INSERT_ID();
select semester_id into semester from division where institute_id=institute_id and standard_id=standard_id limit 0,1;
insert into student_info (roll_no,is_active,institute_id,student_id,standard_id,semester_id,division_id,academic_year_id,maker_id,created_at,updated_at) values (roll_no,'1',institute_id,student_id,standard_id,semester,division_id,academic_year,maker_id,now(),now());
insert into institute_student (is_active,gr_no,institute_id,student_id,admission_standard_id,admission_year_id,created_at,updated_at) values ('1',gr_no,institute_id,student_id,standard_id,academic_year,now(),now());
insert into role_user (user_id,role_id,institute_id,is_active,joining_date,created_at) values (student_user_id,3,institute_id,'1',now(),now());
COMMIT;
SET create_student_result = "success";
SELECT #create_student_result;
END;
ELSE
BEGIN
SET create_student_result = "duplicate_rollno";
SELECT #create_student_result;
END;
END IF;
END;
ELSE
BEGIN
SET create_student_result = "already_exists";
SELECT #create_student_result;
END;
END IF;
END**

MYSQL trigger syntax error. #1064

delimiter //
CREATE TRIGGER Raiting_added AFTER INSERT ON raiting
FOR EACH ROW
BEGIN
declare del INT;
SET del = (SELECT COUNT( rait_id ) FROM `raiting` WHERE NEW.movie_id AND user = NEW.user);
IF del > 0 THEN
DELETE FROM movies WHERE movie_id = NEW.movie_id AND user = NEW.user
END IF;
UPDATE movies
SET raiting = ( SELECT ROUND( AVG( seted_rait ) , 1 )
FROM `raiting`
WHERE movie_id = NEW.movie_id)
WHERE movie_id = NEW.movie_id
END
delimiter;
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 'END IF; UPDATE movies SET raiting = ( SELECT ROUND( AVG(
seted_rait ) , 1 ) ' at line 10
what is problem? can someone help?
You have forgotten "= movie_id" and few semicolons
delimiter //
CREATE TRIGGER Raiting_added AFTER INSERT ON raiting
FOR EACH ROW
BEGIN
declare del INT;
SET del = (SELECT COUNT( rait_id ) FROM `raiting` WHERE NEW.movie_id AND user = NEW.user);
IF del > 0 THEN
DELETE FROM movies WHERE movie_id = NEW.movie_id AND user = NEW.user;
END IF;
UPDATE movies
SET raiting = ( SELECT ROUND( AVG( seted_rait ) , 1 )
FROM `raiting`
WHERE movie_id = NEW.movie_id)
WHERE movie_id = NEW.movie_id;
END;
//
delimiter ;