How to Create Stored Procedure in MySQL - mysql

My tables are
create table employee(
id int(10) auto_increment primary key,
name varchar(100),
addressId int(10)
);
go
create table address(
id varchar(10) auto_increment primary key,
name varchar(100)
);
Here is my procedure
create procedure insert_employee(IN emp_name varchar(100),IN emp_address varchar(100))
begin
DECLARE #addressId varchar(10);
SELECT #addressId:=id from address where name LIKE '%'+emp_address+'%';
IF #addressId = ''
THEN
set #addressId= 'DBS-2136';-- It will come form function
INSERT INTO address values(#addressId,emp_address);
END IF
INSERT INTO employee values(emp_name,#addressId);
END
I don't understand what is the problem. If i write this type of if condition in ms sql server there is not error. every time execute the procedure ti say error in end if. I have search in google but there is not idea about this. there is a problem in declare variable. If i copy form mysql documentation that also not work. why is that?
please help me
1. What is the proper way to declare variable under mysql stored procedure,
2. how to write if condition in mysql stored procedure.
thank you

Lots of differences between mysql and mssql. Declared variables should not include '#', all statements must be terminated, + is an arithmetic operator, if you procedure has multiple statements you must set delimiters before and after.
Further reading
How to declare a variable in MySQL?
https://dev.mysql.com/doc/refman/8.0/en/stored-programs-defining.html

From MySQL reference Manual
An IF ... END IF block, like all other flow-control blocks used within stored programs, must be terminated with a semicolon
IF #addressId = ''
THEN
set #addressId= 'DBS-2136';-- It will come form function
INSERT INTO address values(#addressId,emp_address);
END IF;

Related

I am trying to create email data using an MySQL procedure. How can I go about not inserting into my email table if the data already exists?

Most of the posts I found involve using PHP but I am not using PHP in my case. Here is my MySQL procedure
CREATE DEFINER=`root`#`localhost` PROCEDURE `create_email`(in UID_ int(20),
in user_id_ int(20),
in from_email_ VARCHAR(1024),
in subject_email_ TINYTEXT,
in body_email_ LONGTEXT,
out id_ BIGINT(20) unsigned )
BEGIN
set id_=0;
INSERT INTO emails (UID, user_id, from_email, subject_email, body_email)
VALUES
(UID_ ,user_id_, from_email_, subject_email_, body_email_);
set id_ = LAST_INSERT_ID();
END
Currently my procedure does not check if the data in the table exists it only inserts as the data is being received. What is an effective way of making sure incoming email data does not dublicate onto my emails table?
Thank you in advance.

Stored procedures that dont work?

I am trying to create some stored procedures in my database for my assignment and I can't work out why they don't work correctly as they run, they just don't have the desired effect.
The first is attempting to add members to my table. It runs fine but nothing is added. It just add's 0's for everything.
CREATE DEFINER=`root`#`localhost` PROCEDURE `AddMember`(IN `iFirstname` VARCHAR(15) CHARSET utf8, IN `iLastname` VARCHAR(15) CHARSET utf8, IN `iCPR` INT(10) ZEROFILL, IN `iPhone` INT(8) ZEROFILL, IN `iAddress` VARCHAR(50) CHARSET utf8, IN `iPostcode` INT(4) UNSIGNED, IN `iDateJoined` DATE, IN `iNewsletter` BOOLEAN)
MODIFIES SQL DATA
SQL SECURITY INVOKER
INSERT INTO members (FirstName,
LastName,
CPR,
PhoneNumber,
Address,
Postcode,
DateJoined,
Newsletter)
VALUES (iFirstname,
iLastname,
iCPR,
iPhone,
iAddress,
iPostcode,
iDateJoined,
iNewsletter)
The second is deleting a member. If I run the DELETE FROM WHERE line by it's self it works fine but when its put into the stored procedure it doesn't work.
CREATE DEFINER=`root`#`localhost` PROCEDURE `DeleteMember`(IN mID INT)
BEGIN
DELETE FROM members WHERE MemberID = mID;
END
I am a bit confused as to what is wrong with them as I am new to this and finding specific answers is difficult especially as most examples are even more complex.
Hello Create an id Field in database table with auto incremented values then you will be able to store values via Stored Procedure returned above

MYSQL TRIGGER with IF condition

I'm a noob im MYSQL and I'm trying to make a trigger who will auto-fill 2 fields(customername, customersurname) in an invoice table. Can anyoane explain me please what I do wrong in that trigger? Thank you very much! :)
CREATE TABLE customer(
customerID INT(6) PRIMARY KEY AUTO_INCREMENT,
customername VARCHAR(20) NOT NULL,
customersurname VARCHAR(20) NOT NULL,
customeraddress VARCHAR(200)
);
CREATE TABLE invoice(
invoiceID INT (6) Primary KEY AUTO_INCREMENT,
customerID INT (6) REFERENCES customer(customerID),
customername VARCHAR(20) REFERENCES customer(customername),
invoicedate DATE,
orderID INT(6) REFERENCES orders(orderID),
products VARCHAR(200) REFERENCES orderlines(productname),
FOREIGN KEY(orderID) REFERENCES orders(orderID)
);
CREATE TRIGGER autofill_invoice BEFORE INSERT ON invoice FOR EACH ROW
BEGIN
IF (new.customerID = customer.customerID,
new.customersurname = customer.customersurname )
THEN
SET new.customername = customer.customername,
new.customersurname = customer.customersurname;
END IF;
END;
As mysql documentation on defining stored programs explains:
If you use the mysql client program to define a stored program containing semicolon characters, a problem arises. By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the delimiter temporarily to cause mysql to pass the entire stored program definition to the server.
To redefine the mysql delimiter, use the delimiter command. The
following example shows how to do this for the dorepeat() procedure
just shown. The delimiter is changed to // to enable the entire
definition to be passed to the server as a single statement, and then
restored to ; before invoking the procedure. This enables the ;
delimiter used in the procedure body to be passed through to the
server rather than being interpreted by mysql itself.
So, use the delimiter command when you define the stored procedure:
DELIMITER //
CREATE TRIGGER autofill_invoice BEFORE INSERT ON invoice FOR EACH ROW
BEGIN
IF (new.customerID = customer.customerID,
new.customersurname = customer.customersurname )
THEN
SET new.customername = customer.customername,
new.customersurname = customer.customersurname;
END IF;
END//
DELIMITER ;
Next time pls provide exact error description in your question!

Creating a MySQL Stored Procedure To Add a File To End of Existing Table

I am trying to create a stored procedure that will allow me to input a file, year, and string, and add it to the end of an existing table in MySQL. However, when I attempt to call the program it does not recognize the input file as a variable in the FROM clause. Does anyone have any tips for correcting this issue? I'm new to creating SQL programs but have looked into dynamic SQL, and was wondering if that might be an alternative? Thanks in advance for your help, and I'm happy to post any additional information.
Source File columns are ACS_Code and Descriptive_Title,
Output table columns are Year, Data_Profile, ACS_Code, and Descriptive_Title.
DELIMITER //
DROP PROCEDURE IF EXISTS `padata`.`Load_ACS_Data_Profile_Code_Def`//
CREATE PROCEDURE `padata`.Load_ACS_Data_Profile_Code_Def(IN file VARCHAR(255), IN Data_Profile Varchar(50), IN Year INT) # Input("Social","Economic","Housing",or "Demographic_Housing") for Dataprofile
BEGIN
INSERT INTO padata.ACS_5yr_Selected_Code_Definitions(
Year,
Data_Profile,
ACS_Code,
Descriptive_Title)
SELECT
Year AS Year,
Data_Profile AS Data_Profile,
a.ACS_Code AS ACS_Code,
a.Descriptive_Title AS Descriptive_Title
FROM
`padata`.file a ; #Where file is a parameter that is passed
END //
DELIMITER ;
And here is the call command and error information:
CALL `padata`.Load_ACS_Data_Profile_Code_Def ('2010_5yr_Selected_Social_Metadata', 'Social', 2010)
Error Code: 1146. Table 'padata.file' doesn't exist
what is file, it seems to me you are referring to an file on your operating system. Don't say it is an input file. It is a varchar (string).
It certainly isn't a table in db called padata.
The stored proc IN means you are passing in a parameter such as a string, int sort of thing. It does not open up a stream reading from a file.
Edit:
drop schema so_gibberish;
create schema so_gibberish;
use so_gibberish;
create table thisTable
(
id int not null auto_increment primary key,
favF int not null,
fullName varchar(100) not null
);
insert thisTable (fullName,favF) values ('Jimmy Johnson',2),('Kelly Kipper',3);
create table thatTable
(
id int not null auto_increment primary key,
favF int not null,
fullName varchar(100) not null
);
insert thatTable (fullName,favF) values ('Jennie Jugggs',1),('Zach Zipper',4);
create table favFruit
(
id int not null auto_increment primary key,
fruit varchar(100) not null
);
insert favFruit(fruit) values ('banana'),('kiwi'),('raspberries'),('honey dew melon');
DELIMITER $$
drop procedure if exists so_gibberish.doSomething$$
CREATE PROCEDURE so_gibberish.doSomething
(tblName varchar(100))
BEGIN
SET #statement=concat('select p.fullName,f.fruit from ',tblName,' p join favFruit f on f.id=p.favF');
PREPARE stmt FROM #statement;
execute stmt;
deallocate prepare stmt;
END;
$$
DELIMITER ;
call doSomething('thisTable');
Jimmy Johnson kiwi
Kelly Kipper raspberries
call doSomething('thatTable');
Jennie Jugggs banana
Zach Zipper honey dew melon

Rollback without START TRANSACTION statement is not working in MySQL Stored Procedure

I am using mysql v5.6.
After inserting duplicate record in users table through stored procedure It throws an exception and this is good but unable to rollback for table POSTS.
Here is SQL codes for SP :
DELIMITER //
CREATE PROCEDURE usp_add_user_tests
( IN `i_name` VARCHAR(50),
IN `i_email` VARCHAR(100),
IN `i_status` TINYINT(1) UNSIGNED,
OUT `p_sqlcode` INT(11) UNSIGNED,
OUT `p_status_message` VARCHAR(100)
)
MODIFIES SQL DATA
BEGIN
DECLARE duplicate_key CONDITION FOR 1062;
DECLARE EXIT HANDLER FOR duplicate_key
BEGIN SET p_sqlcode=1062; SET p_status_message='Duplicate key error';
ROLLBACK ;
END;
SET p_sqlcode=0;
INSERT INTO posts (title)
VALUES('test');
INSERT INTO users (name,email,status)
VALUES(i_name,i_email,i_status);
IF p_sqlcode<>0 THEN
SET p_status_message=CONCAT(p_status_message,' when inserting new user');
ELSE
SET p_status_message='Success';
END IF;
END //
DELIMITER ;
Is it possible to rollback for table posts without using Start Transaction statement.
I don't think you have actually started a "transaction". I am pretty sure that you need to implement one of the mechanisms listed here: https://dev.mysql.com/doc/refman/5.7/en/commit.html