Mysql SP with custom arguments - mysql

Im new to mysql stored procedure. Here I have a table tbl_users with following fields
id
first_name
last_name
status
I have written following SP to update this table.
CREATE PROCEDURE `user_update`(IN var_id INT, IN var_first_name TEXT, IN var_last_name TEXT, IN var_status INT)
BEGIN
UPDATE tbl_users SET first_name = var_first_name, last_name = var_last_name, status = var_status WHERE id = var_id;
END
The above procedure will work fine. The problem, I want to use the same procedure to update the only status field. In this situation I have to pass all params with existing values. Is there any solution, If possible I can reuse the SP in multiple areas... pls help.

Mr. EKL please try this code,
You have to include a new parameter "Update_Field" and try the below code
CREATE PROCEDURE `user_update`(
IN var_id INT,
IN var_first_name TEXT,
IN var_last_name TEXT,
IN var_status INT,
IN Update_field TEXT
)
BEGIN
UPDATE tbl_users SET first_name = var_first_name, last_name = var_last_name, [status] = var_status WHERE id = var_id AND Update_field = 'ALL';
UPDATE tbl_users SET [status] = var_status WHERE id = var_id AND Update_field = 'status';
END

Related

How stored procedure output instead of rows count?

My stored procedure always returns 0. I tried unique data and duplicated but the insert is done with success but the return value is always the same #new_identity = 0
CREATE PROCEDURE [dbo].[spAddAuthor]
#Author tyAuthor READONLY,
#new_identity INT = NULL OUTPUT
AS
BEGIN
SET NOCOUNT ON;
-- check if the author exists
IF NOT EXISTS (SELECT Id_Author FROM dbo.Authors
WHERE (dbo.Authors.Username = (SELECT Username FROM #Author)
OR dbo.Authors.phone = (SELECT phone FROM #Author)
OR dbo.Authors.email = (SELECT email FROM #Author)))
BEGIN
INSERT INTO dbo.Authors (Username, sexe, email, phone, address)
SELECT [Username], [sexe], [email], [phone], [address]
FROM #Author
-- output the new row
SELECT #new_identity = ##IDENTITY;
END
ELSE
BEGIN
-- get the author Id if already exists
SELECT #new_identity = (SELECT TOP 1 Id_Author
FROM dbo.Authors
WHERE (dbo.Authors.Username = (SELECT Username FROM #Author)
OR dbo.Authors.phone = (SELECT phone FROM #Author)
OR dbo.Authors.email = (SELECT email FROM #Author)))
END
END
I found that in the declaration of the parameters I put null beside the output and that what caused the problem.
#new_identity INT = NULL OUTPUT
but I don't understand why, I thought the 'null' was like the default value, or when you try to make the parameter optional you add null as default value.
can someone explain, please?

Create a table if given a procedure

I am trying to create a table in a database based on a procedure that was created. I am not to familiar with MySQL procedures to be able to try and create this database.
Here's the code for the procedure:
DELIMITER //
CREATE PROCEDURE SetChanProps(IN vchanmask TEXT, in vchankey TEXT, IN vcommentxt TEXT, IN ventrymsg TEXT, IN vexpires TIMESTAMP, IN vgroupname TEXT, IN vchanlimit INT, IN vmodes TEXT, IN vonlyowner INT, IN vsetbynick TEXT, IN vsetbyhost TEXT, IN vsetbypid INT, IN vtopic TEXT, IN vkickexisting INT)
BEGIN
DECLARE msgid int;
DECLARE rowcount int;
DECLARE setondate TIMESTAMP;
SET setondate = CURRENT_TIMESTAMP;
SELECT COUNT(*) INTO rowcount FROM `chanprops` WHERE `chanmask` = vchanmask;
if rowcount > 0 THEN UPDATE `chanprops` SET `chankey` = vchankey, `comment` = vcommentxt, `entrymsg` = ventrymsg, `expires` = vexpires, `groupname` = vgroupname, `limit` = vchanlimit, `mode` = vmodes, `onlyowner` = vonlyowner, `setbynick` = vsetbynick, `setbyhost` = vsetbyhost, `setbypid` = vsetbypid, `topic` = vtopic, `setondate` = setondate WHERE `chanmask` = vchanmask;
ELSE INSERT INTO `chanprops` (`chanmask`,`chankey`,`comment`,`entrymsg`,`expires`,`groupname`,`limit`,`mode`,`onlyowner`,`setbynick`,`setbyhost`,`setbypid`,`topic`) VALUES (vchanmask,vchankey,vcommentxt,ventrymsg,vexpires,vgroupname,vchanlimit,vmodes,vonlyowner,vsetbynick,vsetbyhost,vsetbypid,vtopic);
end if;
SET msgid = 36;
select matrixqueue(msgid,vchanmask,vchankey,vcommentxt,ventrymsg,Unix_Timestamp(vexpires),vgroupname,vchanlimit,vmodes,vonlyowner,vsetbynick,vsetbyhost,vsetbypid,vtopic,Unix_Timestamp(setondate),vkickexisting);
END//
DELIMITER ;
Is this the correct line to gather what I need to make this table?
ELSE INSERT INTO `chanprops` (`chanmask`,`chankey`,`comment`,`entrymsg`,`expires`,`groupname`,`limit`,`mode`,`onlyowner`,`setbynick`,`setbyhost`,`setbypid`,`topic`) VALUES (vchanmask,vchankey,vcommentxt,ventrymsg,vexpires,vgroupname,vchanlimit,vmodes,vonlyowner,vsetbynick,vsetbyhost,vsetbypid,vtopic);
Would I then use the CREATE PROCEDURE line (Line #2) to determine that types for the the column IDs?
Unfortunately, the project I am trying to utilize this procedure on hasn't been worked on in years and has been abandoned by its creator. They've included other .sql files that usually just create the tables for me. They seemed to have missed this one which conveniently is the one I really care about.

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 ;

Create stored procedure to modify row if it exist and insert new row into table if it doesnt

How can I create a stored procedure to update the Std_Course's column based on the Id and Name parameter, OR inserts a new row if the Id and Name does not exist
Try something like this:
CREATE PROCEDURE dbo.proc_InsertOrUpdate
#ID INT, #Name VARCHAR(50), #StdCourse INT
AS
IF EXISTS (SELECT * FROM dbo.YourTable WHERE ID = #ID AND Name = #Name)
UPDATE dbo.YourTable
SET Std_course = #StdCourse
WHERE ID = #ID AND Name = #Name
ELSE
INSERT INTO dbo.YourTable(ID, Name, Std_Course)
VALUES(#ID, #Name, #StdCourse
Update: since you're on SQL Server 2008, you could also use a simple MERGE statement - either directly "inline" or inside the stored procedure. It would look something like this:
CREATE PROCEDURE dbo.proc_InsertOrUpdate
#ID INT, #Name VARCHAR(50), #StdCourse INT
AS
MERGE dbo.YourTable AS t
USING (SELECT #ID, #Name, #StdCourse) AS Source(ID, NAME, Std_Course)
ON source.ID = t.ID AND source.Name = t.Name
WHEN MATCHED THEN
UPDATE SET Std_Course = #StdCourse
WHEN NOT MATCHED THEN
INSERT(ID, Name, Std_Course)
VALUES(source.ID, source.Name, source.Std_Course);