Procedure that does not UPDATE a table row - mysql

I have this procedure (don't bother too much to figure it out what it does, aim for comments named "Modify 1,2,3,4" )
/* PROCEDURE 1 : Post notification */
DROP PROCEDURE IF EXISTS AddNotificationOnPosts;
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `AddNotificationOnPosts`(arg_from_user INT(11),arg_on_post_id INT(11),arg_in_group_id INT(11))
BEGIN
DECLARE num_rows INT DEFAULT NULL;
DECLARE insert_result INT DEFAULT NULL;
DECLARE user_id INT DEFAULT NULL;
DECLARE done INT DEFAULT 0;
DECLARE var_user_id INT DEFAULT NULL;
DECLARE c1 CURSOR FOR
SELECT user_id
FROM user_rights
WHERE user_rights.right = 101 AND user_rights.group_id = arg_in_group_id
ORDER BY user_id DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
IF(arg_from_user IS NULL OR arg_from_user = '')
THEN
SELECT "0" AS response;
ELSEIF(arg_on_post_id IS NULL OR arg_on_post_id = '')
THEN
SELECT "0" AS response;
ELSEIF(arg_in_group_id IS NULL OR arg_in_group_id = '')
THEN
SELECT "0" AS response;
ELSE
SELECT count(notification_id) FROM notifications_posts
WHERE
from_user = arg_from_user AND
on_post_id = arg_on_post_id AND
in_group_id = arg_in_group_id
INTO num_rows;
/* MODIFY 1*/
UPDATE user_info SET notifications = 1 WHERE user_id = 145;
END IF;
IF num_rows = 0
THEN
INSERT INTO notifications_posts(from_user,on_post_id,in_group_id) VALUES(arg_from_user,arg_on_post_id,arg_in_group_id);
SELECT ROW_COUNT() INTO insert_result;
/* MODIFY 2*/
UPDATE user_info SET notifications = 1 WHERE user_id = 1;
IF insert_result > 0
THEN
/* MODIFY 3*/
UPDATE user_info SET notifications = 1 WHERE user_id = 5;
/* Increment the notifications for every user*/
OPEN c1;
read_loop: LOOP
FETCH c1 INTO var_user_id;
IF done THEN
LEAVE read_loop;
ELSE
/* MODIFY 4*/
UPDATE user_info SET notifications = 1 WHERE user_id = 1;
END IF;
END LOOP;
CLOSE c1;
SELECT "1" AS response;
ELSE
SELECT "0" AS response;
END IF;
ELSE
SELECT "0" AS response;
END IF;
END $$
DELIMITER ;
This works just fine, except the lines
UPDATE user_info SET notifications = 1 WHERE user_id = 1;
won't work, but in simple plain SQL(phpmyadmin) this query is working fine. What is the problem?
What this script does? It helps me be able to post a notification to certain users, and when you post something in group1 all users that have right101 on that group must be notified like
UPDATE user_info SET notifications = notifications + 1 WHERE user_id = var_user_id;
using a cursor as a FOR LOOP like i used to have in PHP
What is wrong with this? Can't a procedure update data?!
Hope i made myself understandable.

Not to sound presumptuous but does the data allow you to get past the
IF num_rows = 0
As a tip though if you are running in SQL Management studio you can debug your sql with breakpoints like normal code. I suggest putting a breakpoint on that line and see if it actually gets hit at all.

How about something along these lines? I usually work in SQL Server, so I apologize if some of the syntax is off, but I threw in some comments, so I hope you get the gist.
/* PROCEDURE 1 : Post notification */
DROP PROCEDURE IF EXISTS AddNotificationOnPosts;
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `AddNotificationOnPosts`(arg_from_user INT(11), arg_on_post_id INT(11), arg_group_id INT(11))
BEGIN
-- sanity checks
IF(arg_from_user IS NULL OR arg_from_user = '')
THEN
RETURN 0;
ELSEIF(arg_on_post_id IS NULL OR arg_on_post_id <= 0)
THEN
RETURN 0;
ELSEIF(arg_in_group_id IS NULL OR arg_in_group_id <= 0)
THEN
RETURN 0;
END IF;
BEGIN TRAN;
-- insert if notification post does not exist
IF NOT EXISTS
(
SELECT *
FROM notification_posts
WHERE
from_user = arg_from_user AND
on_post_id = arg_on_post_id AND
in_group_id = arg_in_group_id
)
THEN
INSERT INTO notifications_posts
(
from_user,
on_post_id,
in_group_id
)
VALUES
(
arg_from_user,
arg_on_post_id,
arg_in_group_id
);
END IF;
-- update all users with 101 right
UPDATE ui
SET notifications = notifications + 1
FROM user_info ui
JOIN user_rights ur on ur.user_id = ui.user_id
WHERE ur.right = 101 and ur.group_id = arg_in_group_id
COMMIT;
END $$
DELIMITER ;

Related

declaring variable inside mysql stored procedure

we are trying to declare a variable inside mysql stored procedure that has transaction implemented in it. but it seems to be giving a syntax error :
following is the syntax of the stored procedure:
CREATE PROCEDURE `sp_MarkAppointmentRefferal`(
p_AppId bigint,
p_NewLocation bigint,
p_userId bigint,
p_ReferralReason varchar(500),
p_NewLocationName varchar(100)
)
begin
declare v_OldLocation int default 0;
set v_OldLocation = (select LocationId FROM appointments where iAppID = p_AppId limit 1 );
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
select -1;
END;
START TRANSACTION;
update table
set is_referred = 1,
referred_timestamp = now(),
referral_reason = p_ReferralReason
where iAppID = p_AppId
limit 1;
-- create a new appointment for the new referred location..
insert into appointments
(vAppName, vAppType, dAppDate, vCell, iPatID, iAppStatus, iuserid, iActive,
dInsertDate, iHSID, daily_ticket_no, LocationId, visit_id, encounter_id, ReferredFrom,ReferredOPDName, opd_name )
select vAppName, vAppType, now(), vCell, iPatID, iAppStatus, p_userId,
1, now(), iHSID, fn_GenerateNextAppointmentTicket(now(),p_NewLocation) , p_NewLocation, visit_id, encounter_id+1,
(select LocationId FROM appointments where iAppID = p_AppId limit 1),
(select OPD_Name FROM appointments where iAppID = p_AppId limit 1), p_NewLocationName
FROM appointments
where iAppID = p_AppId limit 1;
select LAST_INSERT_ID();
COMMIT;
end;
the syntax checker is saying that declare command is not valid here.
have also tried to place this inside the transaction clause and similar error shows up ..
any help is appreciated..
All declare statements should be at the top of the stored procedure body. Moving DECLARE EXIT HANDLER before the SET statement should fix the problem.

1172 - Result consisted of more than one row in mysql

How can I solve this problem (Result consisted of more than one row in mysql)
DROP PROCEDURE IF EXISTS `doMarksApplication`;
CREATE PROCEDURE `doMarksApplication`(
in kuser varchar(20),
out idpro int(11))
SP:BEGIN
declare no_more_rows int default FALSE;
declare total_marks decimal(10,2) default 0;
declare idfor int(11) default 0;
declare sskod int(5) default getCurSession();
declare bdata int(5) default 0;
declare nopmh varchar(20);
# Data PB [Permohonan Baru] DM [Proses Pemarkahan]
declare cur1 cursor for
select ind_nopmh from pinduk
left join pprses on pro_nopmh = ind_nopmh
where ind_sskod = sskod and
concat(pro_stats,pro_statp) in ('PB','DM') and
not exists (select mar_idnum from pmrkah where mar_nopmh = ind_nopmh)
order by ind_nopmh;
declare continue handler for not found set no_more_rows = TRUE;
begin
select count(ind_nopmh) into bdata
from pinduk
left join pprses on pro_nopmh = ind_nopmh
where ind_sskod = sskod and
concat(pro_stats,pro_statp) in ('PB','DM') and
not exists (select mar_idnum from pmrkah where mar_nopmh = ind_nopmh);
end;
begin
select count(for_idnum) into idfor from xkod_markah_00_formula
where for_stats = 'A' and
curdate() between for_tkhdr and for_tkhhg;
end;
if idfor = 1 and sskod <> 0 then
begin
select for_idnum into idfor from xkod_markah_00_formula
where for_stats = 'A' and
curdate() between for_tkhdr and for_tkhhg;
end;
begin
insert into pprmar
(pma_tkmla,pma_msmla,pma_puser,pma_sskod,pma_idfor,pma_bdata)
values
(curdate(),curtime(),kuser,sskod,idfor,bdata);
end;
begin
select last_insert_id() into idpro;
end;
open cur1;
LOOP1:loop
fetch cur1 into nopmh;
if no_more_rows then
close cur1;
leave LOOP1;
end if;
begin
call getMarksAnakPerak(nopmh,#total_perak);
call getMarksAkademik(nopmh,#total_akdmk);
call getMarksSosioekonomi(nopmh,#total_sosio);
end;
set total_marks = #total_perak + #total_akdmk + #total_sosio;
begin
insert into pmrkah
(mar_idpro,mar_nopmh,mar_idfor,mar_perak,mar_akdmk,mar_sosio,mar_total)
values
(idpro,nopmh,idfor,#total_perak,#total_akdmk,#total_sosio,total_marks);
end;
begin
update pprses
set pro_stats = 'D',
pro_statp = 'M',
pro_tkmsk = curdate(),
pro_msmsk = curtime(),
pro_kuser = kuser
where pro_nopmh = nopmh;
end;
end loop;
begin
update pprmar
set pma_tktmt = curdate(),
pma_mstmt = curtime()
where pma_idnum = idpro;
end;
end if;
END;
i have been programming in mysql for 15 years and this is easily the most confusing stored procedure i have ever seen.
None the less, one possible place for your issue is here
select for_idnum into idfor from xkod_markah_00_formula
where for_stats = 'A' and
curdate() between for_tkhdr and for_tkhhg;
I know it does not seem to be the reason but without knowing the content of the other three stored procedures you are calling this is the only candidate. You should add a limit 1 to it, and to every select into statement that reads from a table (i.e. not a sum() or a count() etc...) as that would always have the potential to cause the error you are seeing.
select for_idnum into idfor from xkod_markah_00_formula
where for_stats = 'A' and
curdate() between for_tkhdr and for_tkhhg limit 1;
In addition, you should comment out the three stored procedure calls and see if the error goes away. My guess is that the issue is one of those stored procedures due to a select into similar to above has more than one row in the result set but does not use limit 1 and does not filter properly.

How to find problems in MySQL stored procedure?

I have the following stored procedure:
DELIMITER $$
CREATE DEFINER=`195414_py82740`#`%` PROCEDURE `getUserMail`(inUserId INT)
BEGIN
DECLARE done INT default 0;
DECLARE tmpMailId INT default -1;
DECLARE tmpFromUserId INT default -1;
DECLARE cursor1 cursor for select id from mail WHERE toUserId=inUserId OR fromUserId=inUserId ORDER BY sentDate desc;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
DROP TEMPORARY TABLE IF EXISTS temp_userMail;
CREATE TEMPORARY TABLE temp_userMail LIKE mail;
OPEN cursor1;
REPEAT
FETCH cursor1 INTO tmpMailId;
SET tmpFromUserId = IF ((SELECT fromUserId FROM mail WHERE id=tmpMailId)=inUserId, (SELECT toUserId FROM mail WHERE id=tmpMailId), (SELECT fromUserId FROM mail WHERE id=tmpMailId));
IF EXISTS(SELECT id FROM temp_userMail WHERE fromUserId=tmpFromUserId || toUserId=tmpFromUserId) THEN
SET tmpMailId = 0;
ELSE
INSERT INTO temp_userMail
(`id`,
`fromUserId`,
`toUserId`,
`sentDate`,
`readDate`,
`message`,
`fromUserNickName`,
`toUserNickName`,
`subject`,
`fromUserDeleted`,
`toUserDeleted`)
SELECT
(m1.id,
m1.fromUserId,
m1.toUserId,
m1.sentDate,
m1.readDate,
m1.message,
m1.fromUserNickName,
m1.toUserNickName,
m1.subject,
m1.fromUserDeleted,
m1.toUserDeleted)
FROM mail m1
WHERE m1.id=tmpMailId;
END IF;
UNTIL(done = 1)
END REPEAT;
CLOSE cursor1;
SELECT * FROM temp_userMail ORDER BY sentDate DESC;
END
The SP is saved successfully but when running it I get the cryptic exception
Error Code: 1241: Operand should contain 1 column(s).
I know what the error means but there is no line nr so I have no idea where to look for the problem?
Remove brackets from Your SELECT subquery
dont use
SELECT (id, ... m1.toUserDeleted) ...
use
SELECT id, ... m1.toUserDeleted ...

mysql stored procedure error (1172, 'Result consisted of more than one row')

When trying to run the following stored procedure from django, I get an OperationError (1172, 'Result consisted of more than one row') Any idea what I might be doing wrong?
-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `UpdatePrices`(IN storeId int, IN bottleSize VARCHAR(50))
BEGIN
DECLARE amount DECIMAL(10,2); DECLARE isCustom INT DEFAULT 0;
DECLARE changeType VARCHAR(50) DEFAULT 'State'; DECLARE updateType INT DEFAULT 0;
IF bottleSize = '1000 Ml' THEN
SELECT S1000IncreaseChoices INTO changeType FROM store_store WHERE StoreID = storeId;
IF changeType = 'State' THEN
SELECT updateType = 0;
END IF;
IF changeType = 'Flat' THEN
SELECT S1000IncreaseAmount INTO amount FROM store_store WHERE StoreID = storeId;
SELECT updateType = 1;
END IF;
IF changeType = 'Percent' THEN
SELECT 1 - S1000IncreaseAmount/100 INTO amount FROM store_store WHERE StoreID = storeId;
SELECT updateType = 2;
END IF;
END IF;
IF updateType = 0 THEN
update store_storeliquor SL
inner join liquor_liquor LL
on liquorID_id = id
set StorePrice = ShelfPrice
where BottleSize = bottleSize
and storeID_id = storeId
and custom = 0;
END IF;
IF updateType = 1 THEN
update store_storeliquor SL
inner join liquor_liquor LL
on liquorID_id = id
set StorePrice = OffPremisePrice + amount
where BottleSize = bottleSize
and storeID_id = storeId
and custom = 0;
END IF;
IF updateType = 1 THEN
update store_storeliquor SL
inner join liquor_liquor LL
on liquorID_id = id
set StorePrice = OffPremisePrice / amount
where BottleSize = bottleSize
and storeID_id = storeId
and custom = 0;
END IF;
END
I'm not sure if it matters, but I initiate the stored procedure like so:
def priceupdate(request, store_id):
cursor = connection.cursor()
cursor.callproc("UpdatePrices", (store_id, '1000 ML'))
cursor.close()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Your SELECT...INTO queries give result sets with more then one record. The WHERE filters are incorrect - they compare two the same values StoreID = storeId. Rename IN storeId int parementer to another name. For example - IN storeId_param int
The query will be like this -
SELECT S1000IncreaseChoices INTO changeType FROM store_store WHERE StoreID = storeId_param;
This is a Bug and you need to apply something like that:
SELECT id,data INTO x,y FROM test.t1 LIMIT 1;

mysql trigger function

I have a table call lp_upload and it contain plate number of car and other related information:
CREATE TABLE `lp_upload` (
`date` date NULL ,
`plate` char(10) NULL ,
`site` int NULL ,
`dateid` char(20) NULL
)
;
this table is getting information from a traffic camera. however, sometime letter in the plate is not recognized and it will be replace by $. So if a plate is really abc123, but the camera didnt recognized c and 1, it will be ac$$23 that get enter into the table.
im suppose to make it so when a new plate is entered and 6 of its letters match an existing plate, it will become that plate. EX: 123$5678 is entered and 12345678 already exist, then 123$5678 will be replace by 12345678.
so i first wrote a match function:
CREATE DEFINER = CURRENT_USER FUNCTION `matchingfun`(`str1` char(10),`str2` char(10))
RETURNS int
BEGIN
DECLARE myindex int DEFAULT 0;
DECLARE count int DEFAULT 0;
DECLARE maxlength int;
SET maxlength = length(str1);
for_loop: LOOP
SET myindex = myindex + 1;
IF maxlength < myindex then
RETURN 0;
END IF;
IF SUBSTRING(str1,myindex,1)= SUBSTRING(str2,myindex,1)then
SET count = count +1;
END IF;
IF count > 6 then
RETURN 1;
END IF;
IF SUBSTRING(str1,myindex,1)!= SUBSTRING(str2,myindex,1) and SUBSTRING(str1,myindex,1)!= '$' and SUBSTRING(str2,myindex,1)!= '$'then
RETRUN 0;
END IF;
END LOOP for_loop;
RETURN 0;
END
and I added a trigger function to the table
CREATE TRIGGER `trigger1` AFTER INSERT ON `lpr_opt_upload`
BEGIN
declare old_site_id int;
declare old_text char(10);
select lpr_text into old_text from lpr_opt_upload where matchingfun(new.lpr_text, lpr_text) = 1;
if(old_text is not null) then
set new.lpr_text = old_text;
end if;
END
when i run this, the database crashes. can you help fix this problem or suggest a better way to do this. thanks.
I suspect that the problem you're running into is multiple matches. For example, if you have abcd01234 and abcde1234 in the database and attempt to insert abcd$1234, you'll get an error.
Now, I'm going to assume that this application is supposed to match OCR'd license plates from speed cameras or red-light cameras in order to facilitate ticketing of the vehicle owner. If that's the case, then you want to err on the side of caution and not have the system automatically try to pick from multiple candidates and instead have a real human look at the result and confirm the plate number.
So, operating on that assumption:
DELIMITER //
CREATE TRIGGER `attempt_match_existing_plate`
BEFORE INSERT
ON `lp_upload`
FOR EACH ROW BEGIN
DECLARE exist_plate CHAR(10);
DECLARE rowcount INT;
SELECT COUNT(*), plate INTO rowcount, exist_plate FROM lp_upload WHERE platematch(NEW.plate, plate) = 1;
IF (1 = rowcount) AND (exist_plate IS NOT NULL) THEN
SET NEW.plate = exist_plate;
END IF;
END
//
DELIMITER ;
DELIMITER //
CREATE DEFINER = CURRENT_USER
FUNCTION `platematch`(`plate_new` char(10), `plate_exist` char(10))
RETURNS INT
BEGIN
DECLARE myindex INT DEFAULT 0;
DECLARE match_count INT DEFAULT 0;
DECLARE maxlength INT;
SET maxlength = length(plate_new);
for_loop: LOOP
SET myindex = myindex + 1;
IF maxlength < myindex THEN
RETURN 0;
END IF;
IF SUBSTRING(plate_new, myindex, 1) = SUBSTRING(plate_exist, myindex, 1)
THEN
SET match_count = match_count +1;
END IF;
IF match_count >= 6 THEN
RETURN 1;
END IF;
IF SUBSTRING(plate_new, myindex, 1) != SUBSTRING(plate_exist, myindex, 1)
AND SUBSTRING(plate_new, myindex, 1) != '$'
AND SUBSTRING(plate_exist, myindex, 1) != '$'
THEN
RETURN 0;
END IF;
END LOOP for_loop;
RETURN 0;
END
//
DELIMITER ;
In the scenario I described above, abcd$1234 will be inserted into the database as-is instead of just being matched to one of multiple potential results automatically.