update query in MYSQL stored procedure - mysql

When I execute below update query in mysql workbench It will update only 2 rows.
UPDATE usertoken
SET StatusName='Completed',Id=null
WHERE (UserId=45 and BuddyId=46) OR (UserId=46 and BuddyId=45);
but the same query inside the Stored Procedure updates the entire table.
Even I hard coded the user id's inside the Stored procedure nothing changed.
Any Idea's?
UPDATE:
CREATE DEFINER=`root`#`%` PROCEDURE `SubmitResult`(IN userId int,IN buddyID int,IN startTime DATETIME,IN endtime DATETIME,IN questions varchar(255),IN answers varchar(255))
BEGIN
SET #userId = userId;
SET #questions = questions;
SET #answers = answers;
SET #buddyID = buddyID;
SELECT #QuizId := QuizId from usertoken where (UserId=#userId and BuddyId=#buddyID) OR (UserId=#buddyID and BuddyId=#userId) LIMIT 1;
IF #QuizId IS NULL THEN
INSERT INTO QUIZ (QuizStartTime, QuizEndTime, QuizTypeId)
SELECT startTime,endtime,1;
SELECT #newQId := MAX(QuizId) from QUIZ LIMIT 1;
SELECT #userId,#buddyID,#newQId;
/* UPDATE usertoken SET QuizStatusName='Completed',QuizId=#newQId where (UserId=#userId and BuddyId=#buddyID) OR (UserId=#buddyID and BuddyId=#userId); */
UPDATE usertoken SET QuizStatusName='Completed',QuizId=#newQId where UserId=45;
UPDATE usertoken SET QuizStatusName='Completed',QuizId=#newQId where UserId=46;
// Some Statements
END IF;
SET #userId = NULL;
SET #questions = NULL;
SET #answers = NULL;
SET #buddyID = NULL;
SET #startTime = NULL;
SET #endtime = NULL;
SET #QID = NULL;
SET #AID = NULL;
SET #n = NULL;
SET #newQMId = NULL;
SET #newQId = NULL;
SET #QuizId = NULL;
END

My update query works well after prefixing the where condition with table alias name.. Not sure why it got failed but i assume that Stored procedure IN parameter has the same userId attribute and it could be cause..
After prefixing my update query,
UPDATE usertoken t
SET t.StatusName='Completed',t.Id=null
WHERE (t.UserId=45 and t.BuddyId=46) OR (t.UserId=46 and t.BuddyId=45);

Related

return null value in the JSON_EXTRACT

MyJsonArray
[{"ID":"D29","PersonID":"23616639"},{"ID":"D30","PersonID":"22629626"}]
and I want from sql Function set this array in to my Table but return null value in the variable and not set record in My database
my function:
DELIMITER $$
CREATE DEFINER=`toshiari`#`localhost` FUNCTION `setTitleRecords`(`Title` VARCHAR(166) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci, `List` JSON) RETURNS int(4)
BEGIN
DECLARE Item INT;
DECLARE HolderLENGTH INT;
DECLARE ValidJson INT;
DECLARE ID VARCHAR(166);
DECLARE PersonID VARCHAR(166);
DECLARE S1 VARCHAR(166);
DECLARE S2 VARCHAR(166);
SET ValidJson = (SELECT JSON_VALID(List));
IF ValidJson = 1 THEN
SET HolderLENGTH = (SELECT JSON_LENGTH(List));
SET Item = 0;
WHILE Item < HolderLENGTH DO
SET S1 = CONCAT("'$[",Item, "].ID'");
SET S2 = CONCAT("'$[",Item, "].PersonID'");
SET ID = (SELECT JSON_EXTRACT(List,S1));
SET PersonID = (SELECT JSON_EXTRACT(List,S2));
INSERT INTO `Titles`(`ID`,`PersonID`,`Title`) VALUES (ID, PersonID, Title);
SET Item = Item + 1;
END WHILE;
RETURN 3;
ELSE
RETURN 2;
END IF;
END$$
DELIMITER ;
when I use this command in the Sql commands no problem and return true value
SELECT JSON_EXTRACT('[{"ID":"D29","PersonID":"23616639"},{"ID":"D30","PersonID":"22629626"}]','$[0].ID') return "D29"
return
"D29"
but in when run function from this code
return error and said:
SET #p0='DR'; SET #p1='[{\"ID\":\"D29\",\"PersonID\":\"23616639\"},{\"ID\":\"D30\",\"PersonID\":\"22629626\"}]'; SELECT `setTitleRecords`(#p0, #p1) AS `setTitleRecords`;
#4042 - Syntax error in JSON path in argument 2 to function 'json_extract' at position 1
I created a little test, in order to reproduce your issues. Basically you just need to redeclare S1 and S2, in the following way:
SET S1 = CONCAT('$[',Item,'].ID');
SET S2 = CONCAT('$[',Item,'].PersonID');
And that's it. You can check the test in the following url: https://www.db-fiddle.com/f/2TPgF868snjwcHN3uwoSEA/0

MySQL IN Clause in SQL query with User Defined Function

I am using following query to update all the children of particular topic.
UPDATE topics SET reuse = 0 WHERE topic_id IN (SELECT GetChildTopics(187));
Where
SELECT GetChildTopics(187);
returns "188,190,189" but my update query is updating only first row with topic_id = 188, instead of updating first topic only, it should update all 3 topics.
When I put the values manually it works fine.
UPDATE topics SET reuse = 0 WHERE topic_id IN (188,190,189);
Can anyone suggest what's wrong I am doing here?
Here is the code for GetChildTopics MySQL Function
CREATE DEFINER=`root`#`localhost` FUNCTION `GetAncestry`(GivenID INT) RETURNS varchar(1024) CHARSET latin1
DETERMINISTIC
BEGIN
DECLARE rv VARCHAR(1024);
DECLARE cm CHAR(1);
DECLARE ch INT;
SET rv = '';
SET cm = '';
SET ch = GivenID;
WHILE ch > 0 DO
SELECT IFNULL(parent_topic_id,-1) INTO ch FROM
(SELECT parent_topic_id FROM topic_list WHERE id = ch) A;
IF ch > 0 THEN
SET rv = CONCAT(rv,cm,ch);
SET cm = ',';
END IF;
END WHILE;
RETURN rv;
END
Try this;)
UPDATE topics SET reuse = 0 WHERE FIND_IN_SET(topic_id, GetChildTopics(187));

Declaring a variable in mysql trigger

I have a MySQL trigger that is being used to call the rsaencrypt function to encrypt a particular value.
DELIMITER $$
CREATE TRIGGER ssninsertencrypt BEFORE INSERT ON redcap_data
FOR EACH ROW
BEGIN
IF new.project_id = (SELECT ProjectID FROM redcap_encryption)
AND new.field_name = (SELECT FieldName FROM redcap_encryption)
THEN
SET #PublicKey = (SELECT PublicKey FROM redcap_encryption WHERE ProjectID = new.project_id);
SET new.value = rsaencrypt(new.value,#PublicKey);
END IF;
END$$
DELIMITER ;
This seems to be inconsistently working/not working so i'd like to insert the completed statement the trigger produces into another table so can see what is being passed to the rsaencrypt or not passed. I thought i could just do a SET #SQL () like the following
SET #SQL =
(IF new.project_id = (SELECT ProjectID FROM redcap_encryption)
AND new.field_name = (SELECT FieldName FROM redcap_encryption)
THEN
SET #PublicKey = (SELECT PublicKey FROM redcap_encryption WHERE ProjectID = new.project_id);
SET new.value = rsaencrypt(new.value,#PublicKey);
END IF;)
I get syntax errors on this and i'm unsure how best to proceed
Thanks
Resolved this a while ago but forgot to post :-
BEGIN
IF new.field_name = (SELECT FieldName FROM redcap_encryption WHERE new.project_id = ProjectID)
THEN
SET #PublicKey = (SELECT PublicKey FROM redcap_encryption WHERE ProjectID = new.project_id);
SET new.value = rsaencrypt(new.value,#PublicKey);
END IF;
END$$

Update in mysql trigger not working

I'm creating a trigger to execute after an insert is done into my checkin table but my update statement is not working
DELIMITER $$
DROP TRIGGER IF EXISTS checkins_AINS$$
CREATE TRIGGER `checkins_AINS` AFTER INSERT ON `checkins` FOR EACH ROW
BEGIN
DECLARE client_id INT;
DECLARE duplicate_record INTEGER DEFAULT 0;
DECLARE bpoints INT;
DECLARE business_id INT;
DECLARE CONTINUE HANDLER FOR 1062 SET duplicate_record = 1;
SELECT checkinPoints, id INTO bpoints, business_id FROM businesses WHERE id = new.venue_id;
INSERT INTO clients_checkins_summary(client_id, venue_id, first_checkin, last_checkin,visits)
VALUES(new.client_id, new.venue_id, new.createAt, new.createAt,1);
INSERT INTO clients_points_summary(client_id, business_id,current_points)
VALUES(new.client_id, business_id,bpoints);
IF duplicate_record = 1
THEN
UPDATE clients_checkins_summary
SET last_checkin = new.createAt,
visits = visits + 1
WHERE client_id = new.client_id and venue_id = new.venue_id;
UPDATE clients_points_summary
SET current_points = current_points + bpoints
WHERE client_id = new.client_id and business_id = business_id;
END IF;
END$$
DELIMITER ;
Inserting:
insert into checkins(client_id,venue_id,points,createAt,updateAt)
values (52,19,1,now(),now());
for the first time works fine but when the case of update is trigger is entering into the if but is not update the value.
I trace the variables into a table and all the values are correct but update is not been updating anything.
I missing something?
am I missing something?
Possibly this
UPDATE clients_points_summary
SET current_points = current_points + bpoints
WHERE client_id = new.client_id and business_id = business_id;
The problem here is that your local variable business_id and the column name clients_points_summary.business_id are ambiguous. You could disambiguate as follows:
UPDATE clients_points_summary cps
SET cps.current_points = cps.current_points + bpoints
WHERE cps.client_id = new.client_id and cps.business_id = business_id;

MySQL stored procedure INSERT issue

The following scenario applies:
CREATE TEMPORARY TABLE IF NOT EXISTS `smth_table` (
`login` VARCHAR(20),
`password` VARCHAR(20),
`type` INT(11),
`account_state` DECIMAL(12,4)
);
PREPARE Selection FROM
"INSERT INTO `smth_table`
(SELECT ta.`login`, ta.`password`, ta.`type`, ta.`account_state`
FROM tableA ta
INNER JOIN tableB tb ON tb.id_client = ta.id_client
WHERE tb.id_lot = ? AND ta.`type` MOD 2 = 0
AND ta.first_use = '0000-00-00 00:00:00'
AND ta.account_state = 0
LIMIT ?)";
SET #WHERE = var1;
SET #LIMIT = var2;
EXECUTE Selection USING #WHERE, #LIMIT;
DEALLOCATE PREPARE Selection;
DECLARE curs CURSOR FOR
SELECT `password` FROM `smth_table`;
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;
OPEN pin_curs;
get_pass: LOOP
FETCH curs INTO pass;
IF v_finished = 1 THEN
LEAVE get_pass;
END IF;
UPDATE tableA ta INNER JOIN tableB tb
ON tb.id_client = ta.id_client
SET `type` = `type` | 1,
`account_state` = `account_state` + 5
WHERE tb.id_lot = var1
AND `password` = pass;
END LOOP get_pass;
CLOSE curs;
END
Why, when I run this stored procedure, does the temp table populates with more then the limit? Keep in mind that I set the LIMIT with an IN variable passed through the procedure, and it's 10, incidentally. But when I run the procedure it inserts in the temp table more the 100 rows, and I don't understand why, when it should insert only 10.
SOLVED!
The issue relayed on the fact that I was not deleting the table upon creating it again, thus inserting same values over and over again...
DROP TABLE IF EXISTS `smth_table`;
this inserted before creating it and the query's run smooth :-)