mysql procedure questions? - mysql

when the table user delete fail,why the next sql will be exceute.who can give me a full example for mysql procedure.i want to delete example.please help?
use test;
delimiter //
create procedure proc_name(in paramter int)
begin
declare t_error int default 0;
declare continue handler for sqlexception set t_error=1;
set autocommit = 0;
START TRANSACTION;
delete from `user` where id = paramter;
delete from `user_info` where uid = paramter;
if t_error=1 then
rollback;
else
commit;
end if;
end;
//
delimiter ;

Dinel, I would change a little bit of your logic to achieve what you are looking for:
use test;
delimiter //
create procedure proc_name(in paramter int)
begin
declare continue handler for sqlexception set t_error=1;
SET #t_error = 0;
START TRANSACTION;
delete from `user` where id = paramter;
SELECT #t_error := COUNT(*) from `user` where id = paramter;
if #t_error != 0 then
ROLLBACK;
else
DELETE FROM `user_info` WHERE uid = paramter;
COMMIT;
end if;
end;
//
delimiter ;
I didn't try the syntax, but it should work. ;-)

Related

Trigger befor insert

Is it possible to insert a control on the data that insert in a table? In a way that satisfies a specific condition provided, otherwise not
drop function Presente;
delimiter //
create function Presente( Persona_Da_Cercare varchar(16), Data_Legge date) returns int
begin
declare risultato int;
select count(*) into risultato
from PARLAMENTARI_IN_CARICA as pic
where Persona_Da_Cercare = pic.Persona and data_Legge >= pic.Data_Eletto;
if risultato = 0
then
select count(*) into risultato
from STORICO_PARLAMENTARI as sp
where Persona_Da_Cercare = sp.Persona and data_Legge >= sp.Data_Inizio and data_Legge <= sp.Data_Fine;
end if;
return risultato;
end//
set #ultima_legge bigint;
set #ultimo_parlamentare varchar(16);
set #data_legge date;
drop trigger if exists Ultimo_Voto;
delimiter $$
create trigger Ultimo_Voto before insert on VOTO_PALESE
for each row
begin
set #ultima_legge = new.Legge;
set #ultimo_parlamentare = new.parlamentare;
set #data_legge = (select Data_Approvazione from LEGGI where Cod_Legge = new.Legge);
end $$
drop trigger if exists Controllo_Voto_Palese;
delimiter $$
create trigger Controllo_Voto_Palese after insert on VOTO_PALESE
for each row
BEGIN
IF Presente(#ultimo_parlamentare, #data_legge) = 0 THEN
delete from VOTO_PALESE where Legge = #ultima_legge AND Parlamentare = #ultimo_parlamentare;
END IF;
END $$
insert into VOTO_PALESE(Legge, Parlamentare, Voto) values(770, 'MSRMRC01C14L378X', 'astenuto');
when I run the code it gives me this error
Error Code: 1442. Can't update table 'voto_palese' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
I don't understand where the problem is

Not able to run/execute MySQL Triggers

I am creating Trigger into Mysql Workbanch , but not able to create the trigger.
Can Anyone Help me For This.
DELIMITER $$
create TRIGGER Insert_Test
After Delete ON Test
FOR EACH ROW
BEGIN
START TRANSACTION;
DECLARE v_ID INT;
DECLARE v_Error TINYINT;
DECLARE v_AgentID INT;
SELECT v_Error = 0;
v_ID=Old.id;
BEGIN
DELETE Test2 WHERE id = SELECT id FROM Test where id=v_ID;
Rollback;
SET v_Error = 1;
END
IF v_Error = 0;
THEN
COMMIT;
ELSEIF
v_Error = 1;
THEN
ROLLBACK;
END IF;
END
DELIMITER ;
Sql server Trigger
ALTER TRIGGER [dbo].[tr_DelRecordTypeID] ON [dbo].[luRecordType] FOR DELETE
AS
SET NOCOUNT ON
BEGIN TRANSACTION
DECLARE #ID INT, #GroupTypeID INT, #Error BIT, #Msg VARCHAR(500)
SELECT #Error = 0
SELECT #ID = RecordTypeID FROM deleted
SELECT #GroupTypeID = 30
IF EXISTS ( SELECT g.GroupID
FROM luGroup g,
[luGroupDetail] gd
WHERE g.[GroupID] = gd.[GroupID]
AND g.[GroupTypeID] = #GroupTypeID
AND gd.[MemberID] = #ID )
BEGIN
DELETE [agAgent] WHERE [AgentID] = (SELECT TOP 1 AgentID FROM agAgentPayType)
Rollback transaction
SET #Error = 1
END
IF #Error = 0
BEGIN
COMMIT TRANSACTION
END
ELSE
IF #Error = 1
BEGIN
ROLLBACK TRANSACTION
END
This trigger which i am trying to achieve into mysql workbanch, please check
I shall Be thankful,
Thanks
Aman

Return empty table after rollback

Im writing a procedure, I want it to return table if there wasnt any rollbacks, and return empty table / nothing if there was at least 1 rollback.
DELIMITER $$
CREATE PROCEDURE payment(IN amount int, IN profession varchar(50))
BEGIN
DECLARE done BOOL DEFAULT FALSE;
DECLARE salary INT;
DECLARE pes VARCHAR(11);
DECLARE summary INT DEFAULT 0;
DECLARE employee_cursor CURSOR FOR (SELECT RIGHT(PESEL,3), pensja FROM Pracownicy WHERE zawod=profession);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
DROP TEMPORARY TABLE IF EXISTS tmp1;
CREATE TEMPORARY TABLE tmp1(pesel char(11), status varchar(20) DEFAULT 'wyplacono');
SET AUTOCOMMIT =0;
START TRANSACTION;
OPEN employee_cursor;
readLoop : LOOP
FETCH employee_cursor INTO pes,salary;
IF done THEN
LEAVE readLoop;
END IF;
SET summary = summary + salary;
IF( summary > amount ) THEN
ROLLBACK;
END IF;
INSERT INTO tmp1(pesel) VALUES(CONCAT('********',pes));
END LOOP;
CLOSE employee_cursor;
COMMIT;
SELECT * from tmp1;
END $$
DELIMITER ;
As far it works fine when it doesnt rollback, but
INSERT INTO tmp1(pesel) VALUES(CONCAT('********',pes));
seems to ignore transaction :/
move the rollback test to outside the loop.

can't get MySQL query to work

I am trying to create a stored procedure on a Library database for practice mainly.
But it is confusing me slightly. I am using this query to create the procedure, and it says that it is working, and yet when I then call the procedure, it is saying that the procedure does not exist. Note: I am using phpmyadmin on a web database not on a local host.
delimiter $$
create procedure BorrowBook(in theBookID, in theUserID)
begin
declare lim int;
declare num int;
declare loanNumber int;
declare copyNumber int;
set lim = (select Readers.Limit from Readers where Readers.id = theUserID);
set num = (select Count(*) from Loans where Loans.UserID = theUserID);
set loanNumber = (select Count(*) from Loans) + 1;
set copyNumber = (select NumberAvailable from Book where Book.id = theBookID);
if(copyNumber > 0)
if(num<lim)
then
--Add a Loan to the Loans Table
insert into Loans values(loanNumber, theBookId, theUserID, curDate(), 0);
commit;
update Book set Book.NumberAvailable = Book.NumberAvailable - 1 where Book.id = theBookID;
select 'Succesful Update';
else
rollback;
select 'Borrow limit reached';
end if;
else
rollback;
select 'No copies available';
end;
delimiter ;
You are missing the $$ after the last end:
delimiter $$
...
end; $$ <-- add $$ here
delimiter ;
Shouldn't it be
end; $$
delimiter ;
instead of
end;
delimiter ;

temporary table not returning result set in MySQL stored proc

I have a stored proc which inserts rows from a view with ranks into a temporary table.
The temp table is created before I run a cursor loop that inserted values, and SELECT'ed after the loop is done.
However when I CALL medianMessagesPerWeek(); I get an "Error Code : 1329 No data - zero rows fetched, selected, or processed."
If I create the table as a MYISAM table I can manually select the table and confirm that data has been inserted but the stored proc will still give me nothing.
Am I missing something here?
DELIMITER $$
USE `yongopal_metrics`$$
DROP PROCEDURE IF EXISTS `medianMessagesPerWeek`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `medianMessagesPerWeek`()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE tempJoinWeek, tempActiveWeek, rank INT DEFAULT 0;
DECLARE joinWeek, activeWeek, memberNo, messages INT;
DECLARE cur CURSOR FOR SELECT * FROM cohortMessagesPerMemberPerWeek;
DROP TEMPORARY TABLE IF EXISTS medianMessagesPerWeek;
CREATE TEMPORARY TABLE medianMessagesPerWeek
(
joinWeek INT,
activeWeek INT,
memberNo INT,
messages INT,
rank INT
) ENGINE=MEMORY;
OPEN cur;
read_loop: LOOP
FETCH cur INTO joinWeek, activeWeek, memberNo, messages;
IF done THEN
LEAVE read_loop;
END IF;
IF tempJoinWeek = joinWeek AND tempActiveWeek = activeWeek THEN
SET rank = rank + 1;
ELSE
SET tempJoinWeek = joinWeek;
SET tempActiveWeek = activeWeek;
SET rank = 1;
END IF;
INSERT INTO medianMessagesPerWeek VALUES (joinWeek, activeWeek, memberNo, messages, rank);
END LOOP;
CLOSE cur;
SELECT * FROM medianMessagesPerWeek;
DROP TEMPORARY TABLE IF EXISTS medianMessagesPerWeek;
END$$
DELIMITER ;
EDIT
here is what cohortMessagesPerMemberPerWeek looks like
DELIMITER $$
USE `yongopal_metrics`$$
DROP VIEW IF EXISTS `cohortMessagesPerMemberPerWeek`$$
CREATE ALGORITHM=UNDEFINED DEFINER=`root`#`localhost` SQL SECURITY DEFINER VIEW `cohortMessagesPerMemberPerWeek` AS
SELECT
WEEK(`m`.`regDatetime`,0) AS `joinWeek`,
WEEK(`cd`.`sendDate`,0) AS `activeWeek`,
`m`.`memberNo` AS `memberNo`,
COUNT(0) AS `messages`
FROM (`yongopal`.`chatData` `cd`
JOIN `yongopal`.`members` `m`
ON ((`cd`.`sender` = `m`.`memberNo`)))
GROUP BY WEEK(`m`.`regDatetime`,0),WEEK(`cd`.`sendDate`,0),`m`.`memberNo`
ORDER BY WEEK(`m`.`regDatetime`,0),WEEK(`cd`.`sendDate`,0)$$
DELIMITER ;
Looks like you're missing a not found handler for your cur cursor. This is necessary to set your done boolean to true when the fetch statement no longer returns any rows (and hence you have reached the end of the dataset returned by the cursor declaration).
Give this a try:
DELIMITER $$
USE `yongopal_metrics`$$
DROP PROCEDURE IF EXISTS `medianMessagesPerWeek`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `medianMessagesPerWeek`()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE tempJoinWeek, tempActiveWeek, rank INT DEFAULT 0;
DECLARE joinWeek, activeWeek, memberNo, messages INT;
DECLARE cur CURSOR FOR SELECT * FROM cohortMessagesPerMemberPerWeek;
declare continue handler for not found set done := true;
DROP TEMPORARY TABLE IF EXISTS medianMessagesPerWeek;
CREATE TEMPORARY TABLE medianMessagesPerWeek
(
joinWeek INT,
activeWeek INT,
memberNo INT,
messages INT,
rank INT
) ENGINE=MEMORY;
OPEN cur;
read_loop: LOOP
FETCH cur INTO joinWeek, activeWeek, memberNo, messages;
IF done THEN
LEAVE read_loop;
END IF;
IF tempJoinWeek = joinWeek AND tempActiveWeek = activeWeek THEN
SET rank = rank + 1;
ELSE
SET tempJoinWeek = joinWeek;
SET tempActiveWeek = activeWeek;
SET rank = 1;
END IF;
INSERT INTO medianMessagesPerWeek VALUES (joinWeek, activeWeek, memberNo, messages, rank);
END LOOP;
CLOSE cur;
SELECT * FROM medianMessagesPerWeek;
DROP TEMPORARY TABLE IF EXISTS medianMessagesPerWeek;
END$$
DELIMITER ;