error in my first stored procedure--help! - mysql

this is my first stored procedure . i find it very difficult to debug it . help me by spending a little time on this
create procedure myworld.perform_target_proc(
IN inp_usr_id integer,
IN inp_tgt_src_id integer,
IN inp_tgt_src_type varchar(30),
IN inp_tgt_usr_id integer,
IN tgt_usr_msg text,
out tgt_res varchar(30)
)
BEGIN
declare target_count integer
select count(target_id) from target where usr_id=inp_usr_id and tgt_src_id=inp_tgt_src_id and tgt_src_type=inp_tgt_src_type
and tgt_usr_id=inp_tgt_usr_id into target_count
if target_count=0 then
begin
insert into target(usr_id, tgt_src_id, tgt_src_type, tgt_usr_id, tgt_usr_msg) values
(inp_usr_id, inp_tgt_src_id, inp_tgt_src_type, inp_tgt_usr_id, inp_tgt_usr_msg)
set tgt_res = 'new target created'
end
else
set tgt_res = 'target already exist'
end if
END |

Looks like you are missing some semicolons.
create procedure myworld.perform_target_proc(
IN inp_usr_id integer,
IN inp_tgt_src_id integer,
IN inp_tgt_src_type varchar(30),
IN inp_tgt_usr_id integer,
IN tgt_usr_msg text,
out tgt_res varchar(30)
)
BEGIN
declare target_count integer;
select count(target_id) from target where usr_id=inp_usr_id and tgt_src_id=inp_tgt_src_id and tgt_src_type=inp_tgt_src_type
and tgt_usr_id=inp_tgt_usr_id into target_count;
if target_count=0 then
insert into target(usr_id, tgt_src_id, tgt_src_type, tgt_usr_id, tgt_usr_msg) values
(inp_usr_id, inp_tgt_src_id, inp_tgt_src_type, inp_tgt_usr_id, inp_tgt_usr_msg)
set tgt_res = 'new target created';
else
set tgt_res = 'target already exist';
end if;
END |

I'm a SQL Server guy, not a MySQL guy, but in SQL Server this wouldn't even compile: variables need # prefix for one thing. My guess is you want
set #target_count = SELECT count(target_id)....
or better yet avoid the local variable altogether.

Related

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.

How do I create a stored procedure in MySQL that will select data and insert new values?

Hi I am trying to create a database that will check out document numbers per project. I am trying to keep the db server action limited to stored procedures.
The numbering system goes
XXXX-YY-ZZZZ
XXXX is the job number
YY is the document type table reference
ZZZZ is the document specific number and increments from 1 up for each type in each job...
Because of the numbering system, I can not use an auto incremented column... That would be nice... I would have to generate a table for each document type, for each job... unless anyone sees anything I do not? I am pretty new at this, so any help would be appreciated.
Here is what I have for my procedure that I am having issues with.
DELIMITER $$
DROP PROCEDURE IF EXISTS ADD_NEW_DOC$$
CREATE DEFINER=RMDNA#localhost PROCEDURE ADD_NEW_DOC(IN in_job INT, IN in_type VARCHAR(2), IN in_name VARCHAR(32), IN in_desc VARCHAR(512))
BEGIN
SELECT MAX(doc_id) INTO #highnum FROM Doc_Entries WHERE job_id = in_job AND doc_type_ID = in_type$$
IF #highnum = null THEN SET #newnum = 1$$
ELSE SET #newnum = #highnum + 1$$
END IF$$
insert into Doc_Entries (job_id, doc_type_ID, doc_id, doc_name, doc_desc) values (in_job, in_type, #newnum, in_name, in_desc)$$
SELECT #newnum$$
END$$
DELIMITER ;
and the error I am getting is:
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 2
UPDATE:
My attempt has refined...
DROP PROCEDURE IF EXISTS ADD_NEW_DOC;
DELIMITER //
CREATE DEFINER=RMDNA#localhost PROCEDURE ADD_NEW_DOC(IN in_job INT, IN in_type VARCHAR(2), IN in_name VARCHAR(32), IN in_desc VARCHAR(512))
BEGIN
SELECT MAX(doc_id) INTO #highnum FROM Doc_Entries WHERE job_id = in_job AND doc_type_ID = in_type;
IF (#highnum is null) THEN SET #newnum = 1;
ELSE SET #newnum = #highnum + 1;
END IF;
insert into Doc_Entries (job_id, doc_type_ID, doc_id, doc_name, doc_desc) values (in_job, in_type, #newnum, in_name, in_desc);
SELECT #newnum;
END//
DELIMITER ;
Working good now. Learned how to use delimiter properly and fixed a few things that then became obvious.

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 ;

Create an Store Procedure for Insert-Update in Mysql

I'm trying to create a stored procedure to insert or update a record based on an input variable. But when I try to compile the SP simply tells me the following: Code 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 80. And I have not found the solution. Thank you very much for any help you can give me.
My SP code is as follows:
DELIMITER $$
CREATE PROCEDURE `sp_sertup`(IN i_operation CHAR(1),
IN i_system VARCHAR(20),
IN i_subsystem VARCHAR(20),
IN i_ref VARCHAR(20),
IN i_significance VARCHAR(20),
IN i_rank VARCHAR(20),
IN i_implication VARCHAR(20),
IN i_loc1 VARCHAR(20),
IN i_loc2 VARCHAR(20),
IN i_task VARCHAR(20),
IN i_time VARCHAR(20),
IN i_cost1 VARCHAR(20),
IN i_cost2 VARCHAR(20),
IN i_note VARCHAR(20),
IN i_attach VARCHAR(20),
IN i_operation_text VARCHAR(20),
IN i_id_setup INT )
BEGIN
IF (i_operation = 'I') THEN
UPDATE setup_gs SET setup_status = 0 WHERE id_setup = id_setup;
INSERT INTO setup_gs(
SystemLabel,
SubsystemLabel,
RefLabel,
SignificanceLabel,
RankLabel,
ImplicationLabel,
Location1Label,
Location2Label,
TaskLabel,
TimeLabel,
Cost1Label,
Cost2Label,
NoteLabel,
attachmentText,
OperationsText,
setup_status
)
VALUES
(
i_system,
i_subsystem,
i_ref,
i_significance,
i_rank,
i_implication,
i_loc1,
i_loc2,
i_task,
i_time,
i_cost1,
i_cost2,
i_note,
i_attach,
i_operation_text,
1);
IF (i_operation = 'U') THEN
UPDATE
setup_gs
SET
SystemLabel = values(i_system),
SubsystemLabel = values(i_subsystem),
RefLabel = values(i_ref),
SignificanceLabel = values(i_significance),
RankLabel = values(i_rank),
ImplicationLabel = values(i_implication),
Location1Label = values(i_loc1),
Location2Label = values(i_loc2),
TaskLabel = values(i_task),
TimeLabel = values(i_time),
Cost1Label = values(i_cost1),
Cost2Label = values(i_cost2),
NoteLabel = values(i_note),
attachmentText = values(i_attach),
OperationsText = values(i_operation_text),
setup_status = 1
WHERE id_setup = i_id_setup;
END $$
DELIMITER ;
You must finish your IF-statements with END IF in MySQL.
Also, one of your tests is between id_setup and id_setup. It should be between id_setup and i_id_setup.
if you want to create a update stored procedure then follow these steps in mysql command line. it is work perfectly.
create procedure procedure_name(id int, name varchar(40),salary float)
update table_name set name=name,salary=salary from id=id;
firstly you need to create a table. after that write the keyword create procedure and after that write procedure_name() inside the procedure function write the column name.
i took id, name, salary inside the procedure and also provide the type of all after that i wrote simple query that is update table_NAME set name=name, salary=salary where id=id . because i want to change the name and salary of this id. now you use.

MySQL - Error 1064 in Stored Proc SQL

I have written the following stored procedure which in HeidiSQL is giving me an Error 1064 at the line starting with SET pay_ref = SELECT CONCAT('KOS' ...
Let me firstly explain what's going on with this procedure. I have a table gamers with a BIGINT primary key with auto_increment. This proc is supposed to:
Take in some params from the user
Check if the user already exists in the db according to his/her email address, and spits back the word "DUPLICATE" if a reord does exist
Else it does the insert as normal
Then it reads in the ID of the new record created and converts it to a varchar, pads it with leading zeros and then gets concatenated with some other strings
This new string (which should read for example KOS00001ABCDEF) then gets updated to the pay_refcode field >>> this is how we have settled on generating a unique payment reference for the user
If all works out well it updates retval with the newly generated reference code to be read by PHP script.
DELIMITER //
CREATE PROCEDURE `InsertGamer` (
IN p_fname VARCHAR(30),
IN p_lname VARCHAR(30),
IN p_email VARCHAR(255),
IN p_favgame VARCHAR(60),
IN p_pay_suffix VARCHAR(6),
OUT retval VARCHAR(14)
)
BEGIN
DECLARE last_id BIGINT;
DECLARE pay_ref VARCHAR(14);
IF (EXISTS(SELECT * FROM gamers WHERE (email = p_email))) THEN
SET retval = 'DUPLICATE';
ELSE
INSERT INTO gamers (fname, lname, email, favgame, pay_refcode)
VALUES (p_fname, p_lname, p_email, p_favgame, NULL);
SET last_id = LAST_INSERT_ID();
SET pay_ref = SELECT CONCAT('KOS', (SELECT LPAD(CONVERT(last_id, VARCHAR(5)),5,'0')), p_pay_suffix);
UPDATE gamers
SET pay_refcode = pay_ref
WHERE application_id = last_id;
SET retval = pay_ref;
END IF;
END //
I cannot for the life of me figure out what the problem is and would sincerely appreciate any help from you. Thank you very much in advance!
You just need to remove the SELECT keyword from line which you set the value for pay_ref.
SET pay_ref = CONCAT('KOS', LPAD(CONVERT(last_id, CHAR(5)),5,'0'), p_pay_suffix);
full code:
DELIMITER //
CREATE PROCEDURE `InsertGamer` (
IN p_fname VARCHAR(30),
IN p_lname VARCHAR(30),
IN p_email VARCHAR(255),
IN p_favgame VARCHAR(60),
IN p_pay_suffix VARCHAR(6),
OUT retval VARCHAR(14)
)
BEGIN
DECLARE last_id BIGINT;
DECLARE pay_ref VARCHAR(14);
SET #count := (SELECT COUNT(*) FROM gamers WHERE email = p_email)
IF (#count > 0) THEN
SET retval = 'DUPLICATE';
ELSE
INSERT INTO gamers (fname, lname, email, favgame, pay_refcode)
VALUES (p_fname, p_lname, p_email, p_favgame, NULL);
SET last_id = LAST_INSERT_ID();
SET pay_ref = CONCAT('KOS', LPAD(CONVERT(last_id, CHAR(5)),5,'0'), p_pay_suffix);
UPDATE gamers
SET pay_refcode = pay_ref
WHERE application_id = last_id;
SET retval = pay_ref;
END IF;
END //
DELIMITER ;