MySQL INSERT WHERE a variable is not duplicated - mysql

I have some troubles with DECLARE, CALL function and a IF settelment. What i have so far is:
CREATE PROCEDURE number_of_projects(project_name VARCHAR)
BEGIN
DECLARE variable INT;
SET variable = 4;
SELECT variable;
SELECT count(project_id) FROM atm_projects WHERE project_name = variable;
END
IF number_of_projects("PROJECT NAME") = 0
THEN
INSERT INTO atm_projects(project_id,project_name,added_from_mti)
VALUES (project_id,'PROJECT NAME',1)
ENDIF
The main goal is to insert a row into a table where project_name is not duplicated.
I could change project_name to an UNIQUE key but please tell me what is wrong with my code, an how can i fix this?
I need to learn how a PROCEDURE, CALL procedure, IF works.

try:
CREATE PROCEDURE number_of_projects(project_name VARCHAR(255))
BEGIN
DECLARE var_project_no INT;
SET var_project_no = 0;
SELECT var_project_no;
SELECT count(project_id) INTO var_project_no FROM atm_projects WHERE var_project_name = 4;
IF var_project_no = 0
THEN
INSERT INTO atm_projects(project_id,project_name,added_from_mti)
VALUES (project_id,'PROJECT NAME',1)
END IF;
END;

You have declared project_name to varchar without specifying the length. Change it to varchar(100)

CREATE PROCEDURE number_of_projects(project_name VARCHAR(255))
BEGIN
if NOT exists(SELECT Top 1 1 FROM atm_projects WHERE var_project_name = 4)
BEGIN
INSERT INTO atm_projects(project_id,project_name,added_from_mti)
Select project_id,project_name ,1
END
END;

Related

error in stored procedure ...into keyword

Two tables Borrower(rollno,name,bookissue_date) and Fine(rollno,name,amount)
delimiter //
create procedure student( in roll_no int,in Nameofbook varchar(40))
begin
declare Dateofiss1 date;
Declare cur cursor for
select Dateofiss from Borrower where Roll_no = roll into Dateofiss1;
OPEN cur;
fetch cur into Dateofiss1
if(datediff(sysdate(),Dateofiss1)<15) then varchar(20))
update Borrower set status='R'where Roll_no=roll_no
elseif(datediff(sysdate(),Dateofiss1)>=15)and datediff (sysdate(),Dateofiss1<30)
SET FINEAMOUNT=5*(datediff(sysdate(),Dateofiss1)-15)
insert into Fine(Roll_no,Date,amount)values(rollno,sysdate,fineamount);
update.borrower set status='R' where Roll_no='rollno';
elseif (datediff(sysdate(),Dateofiss1)>30)
SET FINEAMOUNT=50*(datediff(sysdate(),Dateofiss1)-15)
insert into Fine(Roll_no,Date,amount)values(rollno,sysdate,fineamount);
update.borrower set status='R' where Roll_no='rollno';
close cur;
end if
select * from Borrower;
elect * from Fine;
end
You have a number of syntax errors.
You have an extraneous varchar(20)) in the first if statement.
You're missing THEN in the ELSEIF statements.
You wrote update.borrower instead of update borrower.
You have roll_no in quotes in some of your update statements.
The roll_no parameter is the same as a table column, since column names are case-insensitive. The condition where Roll_no = roll_no will match every row because of this. Give the parameter a different name.
In a SELECT, the INTO clause goes after FROM, not at the end.
There's no need to use a cursor if you're using SELECT INTO. Just execute the query and it will set the variable.
You can also simplify the code by putting the date difference in a variable, so you don't have to repeatedly calculate it. And in the ELSEIF you don't need to test >= 15, since you'll only get there if the < 15 test failed.
The UPDATE statement is the same in all conditions, so it doesn't need to be in the IF at all.
delimiter //
create procedure student( in p_roll_no int,in Nameofbook varchar(40))
begin
declare Dateofiss1 date;
declare diff INT;
select Dateofiss from Borrower into Dateofiss1 where Roll_no = p_roll_no;
OPEN cur;
SET diff = datediff(sysdate(),Dateofiss1)
IF diff BETWEEN 15 AND 29 THEN
SET FINEAMOUNT= 5 * (diff - 15)
insert into Fine(Roll_no,Date,amount)values(rollno,sysdate,fineamount);
else
SET FINEAMOUNT= 50 * (diff - 15)
insert into Fine(Roll_no,Date,amount)values(rollno,sysdate,fineamount);
end if
update Borrower set status='R'where Roll_no=p_roll_no
select * from Borrower;
select * from Fine;
end

Stored Procedure updates two rows

DELIMITER //
CREATE OR REPLACE PROCEDURE GET_USER_PNTS(USER_ID INT , PNTS INT, QNT INT)
BEGIN
DECLARE x INT DEFAULT 1;
DECLARE TEMP_GIFT_ID INT;
UPDATE USR_PNT_SUMM SET USD_PNTS = USD_PNTS + PNTS WHERE USER_ID = 1;
COMMIT;
END //
DELIMITER ;
The above stored procedure updates two rows - one for user_id = 1 and the other one for userid 0. I dont understand why!
This is how I call the stored procedure -
CALL GET_USER_PNTS(1, 1, 1)
Please let me know why the user_id 0 is also getting updated.
P.S
1. I am using MariaDB.
2. UserID 0 is what I had manually added in the table. In pratice there won't be any 0 user_id. But even then, the row should not have been updated.
Please rename your parameters:
CREATE OR REPLACE PROCEDURE GET_USER_PNTS(L_USER_ID INT , L_PNTS INT, L_QNT INT)
BEGIN
DECLARE x INT DEFAULT 1;
DECLARE TEMP_GIFT_ID INT;
UPDATE USR_PNT_SUMM SET USD_PNTS = USD_PNTS + L_PNTS WHERE USER_ID = L_USER_ID;
COMMIT;
END //
Probably USER_ID = USER_ID is treated as true.

Mysql Stored Proc not returning a VARCHAR out parameter

Below is my stored procedure. It works fine but my problem is I can't get the output parameter as VARCHAR.
The part where I'm having problem is the assignment of #curcName to the out parameter op_resultMessage
BEGIN
SET op_resultMessage = #curcName;
END;
Here's the Stored Procedure.
CREATE DEFINER=`root`#`localhost` PROCEDURE `addCurriculum`(
IN p_curcName varchar(100),
IN p_description TEXT,
IN p_yearLevel VARCHAR(50),
IN p_syStart INT,
IN p_syEnd INT,
IN p_creator VARCHAR(50),
OUT op_resultMessage VARCHAR(50))
BEGIN
DECLARE curcName VARCHAR(20) ;
IF EXISTS
(SELECT #curcName := `name`
FROM curriculum
WHERE
yearLevel = p_yearLevel
AND syStart = p_syStart
AND syEnd = p_syEnd )
THEN --
BEGIN
SET op_resultMessage = #curcName;
END;
ELSE
BEGIN
INSERT INTO curriculum(`name`, description, yearLevel, syStart, syEnd, creator)
VALUES(p_curcName,p_description,p_yearLevel,p_syStart,p_syEnd,p_creator);
END;
END IF;
END
I'm trying to return a message IF name EXISTS
So it should go something like
SET op_resultMessage = #curcName 'already uses the school year and year level you're trying to insert';
But I don't know how to properly concatenate and assign values. I'm still confused with := SET and = operators. I guess that's where I'm having problems with.
If I change the out parameter's type to an INT like
OUT op_resultMessage VARCHAR(50)
then assigns a number to op_resultMessage like SET op_resultMessage = 1;
It returns the number 1 as out parameter values. It just won't work with varchar.
So when I try to call the procedure
CALL `enrollmentdb`.`addCurriculum`
('Test Curriculum ','Test ','Grade 1',2015,2016,'jordan',#outputMsg);
SELECT #outputMsg; -- this doesn't return any value even if Grade 1, 2015 and 2016 exists
I'd appreciate any help. I actually just learned mysql recently.
Thanks.
drop procedure if exists addCurriculum;
delimiter $$
CREATE PROCEDURE `addCurriculum`(
IN p_curcName varchar(100),
IN p_description TEXT,
IN p_yearLevel VARCHAR(50),
IN p_syStart INT,
IN p_syEnd INT,
IN p_creator VARCHAR(50),
OUT op_resultMessage VARCHAR(50))
BEGIN
DECLARE curcName VARCHAR(20) ;
SELECT `name` into #curcName
FROM curriculum
WHERE
yearLevel = p_yearLevel
AND syStart = p_syStart
AND syEnd = p_syEnd
LIMIT 1;
-- Note change above. When selecting into a variable (or more than 1)
-- then 0 or 1 rows can come back max or an Error occurs
IF #curcName is not null then
SET op_resultMessage = #curcName;
ELSE
BEGIN
INSERT INTO curriculum(`name`, description, yearLevel, syStart, syEnd, creator)
VALUES(p_curcName,p_description,p_yearLevel,p_syStart,p_syEnd,p_creator);
END;
SET op_resultMessage = 'GEEZ I am right here'; -- Drew added this
END IF;
END$$
delimiter ;
Note the commentary in the stored procedure, especially the part of only 0 or 1 rows returning else an Error will occur with a select into var pattern. So LIMIT 1. That may or may not be the row you want (limit 1), but that is where it is at right now.

error code 1414 in mysql when i am call store procedure

any body help me..
i am call sp not succses,
--==================================================================================
Query: call `sp_MasterDataPegawai`('','0123555','neni','P','001','001',1,'',null)
Error Code: 1414
OUT or INOUT argument 9 for routine #maninds_std_mwt.sp_MasterDataPegawai is not a variable or NEW pseudo-variable in BEFORE trigger
--==================================================================================
and this is my sp :
--==================================================================================
DELIMITER $$
USE `#maninds_std_mwt`$$
DROP PROCEDURE IF EXISTS `sp_MasterDataPegawai`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_MasterDataPegawai`(
IN p_IdPegawai CHAR(10),
IN NIK CHAR(10),
IN p_NamaLengkap VARCHAR(50),
IN p_JenisKelamin CHAR(1),
IN p_KdDivisi CHAR(3),
IN p_KdJabatan CHAR(3),
IN p_KdStatusAktif TINYINT(1),
IN p_status CHAR(1),
OUT OutputId VARCHAR(10)
)
BEGIN
/* ======Local variabel==========*/
DECLARE pLoc_TempIdPegawai VARCHAR(10);
DECLARE pLoc_TempIdPegawai_i INTEGER;
DECLARE i INTEGER;
DECLARE pLoc_KdTitle CHAR(2);
DECLARE pLoc_KdJenisPegawai CHAR(3);
/*===============================*/
IF p_JenisKelamin = 'L' THEN
SET pLoc_KdTitle = '01';
ELSE
SET pLoc_KdTitle = '02';
END IF;
SET pLoc_KdJenisPegawai = '001';
SELECT pLoc_TempIdPegawai = `IdPegawai`,COUNT(*) FROM `tbl_data_pegawai` WHERE `IdPegawai` = p_IdPegawai;
IF COUNT(*) = 0 THEN
SELECT pLoc_TempIdPegawai_i = MAX(RIGHT(`IdPegawai`,6)) FROM `tbl_data_pegawai` WHERE `IdPegawai` <> '7777777777';
IF pLoc_TempIdPegawai_i IS NULL THEN
SET pLoc_TempIdPegawai = CONCAT(p_JenisKelamin,pLoc_KdJenisPegawai,'000001');
ELSE
SET i = RIGHT(pLoc_TempIdPegawai_i,6) + 1;
SET pLoc_TempIdPegawai = CONCAT(p_JenisKelamin ,`fc_FormatNomor`(pLoc_KdJenisPegawai,3),fc_FormatNomor(i,6));
END IF;
INSERT INTO `tbl_data_pegawai`
(
`IdPegawai`,
`NIK`,
`KdTitle`,
`NamaLengkap`,
`JenisKelamin`,
`TempatLahir`,
`Alamat`,
`TglLahir`
)
VALUES
(
pLoc_TempIdPegawai,
p_NIK,
pLoc_KdTitle,
p_NamaLengkap,
p_JenisKelamin,
NULL,
NULL,
NULL
);
/*insert ke tabel tbl_data_current_pegawai */
INSERT INTO `tbl_data_current_pegawai`
(
`IdPegawai`,
`KdJenisPegawai`,
`KdJabatan`,
`KdDivisi`,
`KdAgama`,
`KdPendidikan`,
`StatusEnabled`
)
VALUES
(
pLoc_TempIdPegawai,
pLoc_KdJenisPegawai,
p_KdJabatan,
p_KdDivisi,
NULL,
NULL,
p_KdStatusAktif
);
SET OutputId = pLoc_TempIdPegawai;
-- else
IF UPPER(p_Status)= 'A' THEN
UPDATE `tbl_data_pegawai`
SET
`IdPegawai`=p_IdPegawai,
`KdTitle`=pLoc_KdTitle,
`NamaLengkap`=p_NamaLengkap,
`JenisKelamin`=p_JenisKelamin
WHERE `IdPegawai`=p_IdPegawai AND `KdTitle`=pLoc_KdTitle;
/* Update tbl_data_current_pegawai */
UPDATE `tbl_data_current_pegawai`
SET
`IdPegawai`=p_IdPegawai,
`KdJabatan`=p_KdJabatan,
`KdDivisi`=p_KdDivisi,
`StatusEnabled`=p_KdStatusAktif
WHERE `IdPegawai`=p_IdPegawai;
ELSE
DELETE FROM `tbl_data_pegawai` WHERE `IdPegawai`=p_IdPegawai;
DELETE FROM `tbl_data_current_pegawai` WHERE `IdPegawai`=p_IdPegawai;
SET OutputId = p_IdPegawai;
END IF;
END IF;
END$$
DELIMITER ;
--==================================================================================
how clear this error?
i am sorry because my english language not good.
thank you
When we specify the parameter as OUT or INOUT, the stored procedure should be able to operate on that parameter. So it expects the paramter to be a variable which the caller can use later. If we specify a VALUE, its not possible for the Stored Procedure to manipulate that value, thus it will throw an 1414 error.
We can pass values only for IN parameter of the Stored procedure.
So define a session variable and then send that variable as a parameter.
13.2.1 CALL Syntax
...
To get back a value from a procedure using an OUT or INOUT parameter,
pass the parameter by means of a user variable, and then check the
value of the variable after the procedure returns. (If you are calling
the procedure from within another stored procedure or function, you
can also pass a routine parameter or local routine variable as an IN
or INOUT parameter.)
...
Try:
-- call `sp_MasterDataPegawai`('','0123555','neni','P','001','001',1,'',null)
call `sp_MasterDataPegawai`('','0123555','neni','P','001','001',1,'',#`_OutputId`);
Need to call the parameters in mysql like this
call sp_MasterDataPegawai('','0123555','neni','P','001','001',1,'',#message);
select #message ;

How i can use variable from a select to call a stored procedure?

My problem it's this code.
DELIMITER $$
DROP PROCEDURE IF EXISTS agregar_abono$$
CREATE PROCEDURE agregar_abono(IN pid_cliente BIGINT, IN pfecha_abono DATE, IN pmonto_abono FLOAT)
BEGIN
DECLARE #idabono BIGINT;
-- OTHER CODE ...
SELECT id_abono AS idabono FROM abono WHERE fk_cliente = pid_cliente ORDER BY id_abono DESC LIMIT 1;
SELECT CONCAT('>', idabono);
CALL cobrar_abono(pid_cliente, vid_abono);
END $$
The procedure of the two SELECT return:
idabono = 52 --> good! (in the first select)
CONCAT('>', idabono) = null ---> what??
I don't know because don't stored the result in this variable to use in a stored procedure. I use a AS to store the variable.
The header of stored procedure to call is :
CREATE PROCEDURE cobrar_abono(IN pid_cliente BIGINT, IN pid_abono BIGINT)
Are you looking for this?
...
DECLARE idabono BIGINT;
-- OTHER CODE ...
SET idabono = (SELECT id_abono
FROM abono
WHERE fk_cliente = pid_cliente
ORDER BY id_abono DESC
LIMIT 1);
The SELECT statement itself probably can be replaced with
SET idabono = (SELECT MAX(id_abono)
FROM abono
WHERE fk_cliente = pid_cliente);