How to declare variables in mysql Stored procedure? - mysql

I want to declare a variable and then assign a value of select query to that particular variable and then I need to pass that variable in an insert statement . So I tried the below code,
DROP PROCEDURE IF EXISTS `pro_damagestockdao` $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `pro_damagestockdao`(
IN damage_date date,
IN damage_inv_no varchar(12),
IN damage_inv_date date,
IN damage_dist_name varchar(30),
IN damage_contact_no varchar(15),
IN damage_item_code varchar(30),
IN damage_item_name varchar(30),
IN damage_batch_no varchar(15),
IN damage_mfr_name varchar(50),
IN damage_expiry_date date,
IN damage_pur_qty int(11),
IN damage_qty int(11),
IN damage_unit_price double(10,2),
IN damage_unit_vat double(4,2),
IN damage_unit_discount double(4,2),
IN damage_sub_total double(10,2),
IN damage_total_amount double(10,2),
IN damage_remarks varchar(1000),
IN functionality varchar(20),
out flag int
)
BEGIN
DECLARE selCnt int;
DECLARE dqty int;
SET dqty = (SELECT free FROM purchase_invoice p WHERE p.invoice_no = damage_inv_no);
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK;
SET flag=0;
START TRANSACTION;
if(functionality='save') then
INSERT INTO damage_stocks
(damage_stock_date,invoice_no,invoice_date,dist_name,contact_no,item_code,item_name,batch_no,qty,damaged_qty,unit_price,unit_vat,unit_discount,sub_total,total_amount,remarks) VALUES
(damage_date,damage_inv_no,damage_inv_date,damage_dist_name,damage_contact_no,0,damage_item_name,damage_batch_no,dqty,damage_qty,damage_unit_price,damage_unit_vat,damage_unit_discount,damage_sub_total,damage_total_amount,damage_remarks);
But it fails.. You see, I declared a variable dqty and then I passed it to the insert statement.

It is not problem to declaration. It is assign problem
try this query
SELECT free into dqty FROM purchase_invoice p WHERE p.invoice_no = damage_inv_no;

The following code works fine for me:
DELIMITER $$
USE `test`$$
DROP PROCEDURE IF EXISTS `pro_damagestockdao`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `pro_damagestockdao`(
IN damage_date DATE,
IN damage_inv_no VARCHAR(12),
IN damage_inv_date DATE,
IN damage_dist_name VARCHAR(30),
IN damage_contact_no VARCHAR(15),
IN damage_item_code VARCHAR(30),
IN damage_item_name VARCHAR(30),
IN damage_batch_no VARCHAR(15),
IN damage_mfr_name VARCHAR(50),
IN damage_expiry_date DATE,
IN damage_pur_qty INT(11),
IN damage_qty INT(11),
IN damage_unit_price DOUBLE(10,2),
IN damage_unit_vat DOUBLE(4,2),
IN damage_unit_discount DOUBLE(4,2),
IN damage_sub_total DOUBLE(10,2),
IN damage_total_amount DOUBLE(10,2),
IN damage_remarks VARCHAR(1000),
IN functionality VARCHAR(20),
OUT flag INT)
BEGIN
DECLARE selCnt INT;
DECLARE dqty INT;
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK;
SET dqty = (SELECT free FROM purchase_invoice p WHERE p.invoice_no = damage_inv_no);
SET flag = 0;
START TRANSACTION;
IF(functionality = 'save') THEN
INSERT INTO damage_stocks (damage_stock_date, invoice_no, invoice_date, dist_name, contact_no, item_code, item_name, batch_no, qty,damaged_qty, unit_price, unit_vat, unit_discount, sub_total, total_amount, remarks)
VALUES (damage_date, damage_inv_no, damage_inv_date, damage_dist_name, damage_contact_no, 0, damage_item_name, damage_batch_no, dqty,damage_qty, damage_unit_price, damage_unit_vat, damage_unit_discount, damage_sub_total, damage_total_amount, damage_remarks);
END IF;
END$$
DELIMITER ;
With this SP call:
CALL `pro_damagestockdao`("2015-06-23","rx45","2015-06-20","DistName","DContactNo","DamageItemCode","damage_item_name","damage_batch_no","damage_mfr_name", "2015-07-01", 10, 5, 15.2, 7.66, 9.88, 99.00, 150.22, "No remarks", "save", #sorin);
What error do you get?
Do you get an error when trying to create the stored procedure or when you call it?

Related

I want to increase or decrease the amount of money in Total_Crédit which is in Credit_electrecité depending on the event to be done

create PROCEDURE PR_Credit_Total(
in newidpiece int,
in newnpiece bigint,
in newnop varchar(60),
in newdateengagement date,
in newdatefacture date,
in newlocalité varchar(50),
in newtournee int,
in newnpolice bigint,
in newservice varchar(20),
in newmontant float,
in newecheance varchar(7),
in newcreated varchar(25),
in eventvarchar(100)
)
BEGIN
set #total=(SELECT sum(Total_Crédit) from credit_electricité) ;
if event=='ajouter'
and newtournee is null
THEN
if #total-newmontant>=0
INSERT into vignetteoneep VALUES(newidpiece,newnpiece,newnop,newdateengagement,
newdatefacture,newlocalité,newtournee,newnpolice,newservice,newmontant,newecheance,newcreated);
then
UPDATE credit_electricité set Total_Crédit=Total_Crédit-newmontant;
end if;
end if;
END
create PROCEDURE PR_Credit_Total(
#newidpiece AS int,
#newnpiece AS bigint,
#newnop AS varchar(60),
#newdateengagement AS date,
#newdatefacture AS date,
#newlocalité AS varchar(50),
#newtournee AS int,
#newnpolice AS bigint,
#newservice AS varchar(20),
#newmontant AS float,
#newecheance AS varchar(7),
#newcreated AS varchar(25),
#event AS varchar(100),
#total AS INT
)
AS
BEGIN
set #total=(SELECT sum(Total_Crédit) from credit_electricité)
if #event = 'ajouter' and #newtournee is null
if #total - #newmontant >=0
INSERT into vignetteoneep VALUES(newidpiece,newnpiece,newnop,newdateengagement,
newdatefacture,newlocalité,newtournee,newnpolice,newservice,newmontant,newecheance,newcreated)
UPDATE credit_electricité set Total_Crédit=Total_Crédit - #newmontant
END
Here's a list of syntax errors to fix
in eventvarchar(100) missing space ,should be in event varchar(100) but event is a keyword and best avoided
if event=='ajouter' null safe equal in mysql is <=> so should be if event <=> 'ajouter' but = would do
The second if does not have a then it's not clear if the insert and update should be part of same condition but I suspect not
if #total-newmontant>=0 then
INSERT ...
else
UPDATE ...
end if;
And you may need to set delimiters

For each supplier(name) show the names of the items it supplies. EXERCISES CURSOR NESTED MySQL

For each supplier(name) show the names of the items it supplies.
Files.sql
I happen to have the following data in my database
Database creation and deletion
DROP DATABASE IF EXISTS almacen;
CREATE DATABASE IF NOT EXISTS almacen;
Create and Add data to the table articulos
USE almacen;
CREATE TABLE articulos(
cod_art VARCHAR(6) PRIMARY KEY,
descripcion VARCHAR(45),
precio FLOAT,
stock INT,
caducidad BOOLEAN,
cod_prov VARCHAR(4),
observaciones VARCHAR(45)
);
INSERT INTO articulos VALUES('DR-001','Lejia',0.80,18,FALSE,'A002','Muy Toxica'),
('DR-002','Suavizante',2.40,10,FALSE,'A001','No volcar'),
('DR-003','Quitamancha',5.00,18,FALSE,'B001','Muy Toxico'),
('PA-001','Pan',1.00,35,TRUE,'B001','No tocar con las manos'),
('PA-002','Palmerita',2.10,8,TRUE,'A001','Aplicar max 5 paquetes'),
('PA-003','Napolitana',1.00,44,TRUE,'A002','Chocolate crema'),
('VE-001','Lechuga',1.50,27,TRUE,'B002','No meter en la nevera'),
('VE-002','Zanahoria',3.00,330,TRUE,'A001','No meter en la nevera');
Create and Add data to the clientes table
CREATE TABLE clientes(
cod_cliente INT AUTO_INCREMENT PRIMARY KEY,
dni VARCHAR(9),
nombreCli VARCHAR(25),
ap1 VARCHAR(35),
ap2 VARCHAR(35),
descuento INT
);
INSERT INTO clientes VALUES(null,'45098765G','Juan','Perez','Soler',5),
(null,'33456739H','Antonio','Garcia','Toro',8),
(null,'23478962S','Ramon','Gonzalez','Tamudo',0),
(null,'45765432F','Jesus','Duarte','Fortes',4),
(null,'29876098G','Gabriel','Lopez','Vazquez',2);
Create and Add data to the detallesFacturas
CREATE TABLE detallesFacturas(
nFactura INT,
cod_art VARCHAR(6),
cantidad INT,
desc_especial INT,
PRIMARY KEY (nFactura,cod_art)
);
INSERT INTO detallesFacturas VALUES(6,'DR-003',5,2),
(6,'PA-002',2,6),
(7,'DR-003',4,0),
(7,'DR-002',2,2),
(8,'VE-002',3,5),
(8,'PA-001',7,5),
(1,'DR-001',2,2),
(1,'PA-002',5,0),
(1,'DR-002',10,4),
(1,'VE-001',3,0),
(2,'DR-002',2,4),
(2,'VE-002',3,5),
(2,'PA-001',2,2),
(3,'PA-002',4,4),
(3,'VE-002',1,3),
(3,'DR-001',3,2),
(4,'PA-001',2,0),
(4,'PA-002',3,5),
(4,'VE-002',2,2),
(5,'VE-001',4,6),
(5,'PA-001',3,3);
Create and Add data to the facturas
CREATE TABLE facturas(
nFactura INT AUTO_INCREMENT PRIMARY KEY,
nCliente INT,
fecha DATE,
forma_pago VARCHAR(20)
);
INSERT INTO facturas VALUES(null,3,'2007-10-10','Contado'),
(null,2,'2007-10-11','Contado'),
(null,5,'2007-10-11','Cheque'),
(null,1,'2007-10-12','Transferencia'),
(null,5,'2007-10-14','Contado'),
(null,1,'2007-10-16','Cheque'),
(null,2,'2007-10-16','Transferencia'),
(null,4,'2007-10-17','Contado');
Create and Add data to the proveedores
CREATE TABLE proveedores(
cod_prov VARCHAR(4) PRIMARY KEY,
nombre_prov VARCHAR(30),
telefono VARCHAR(9),
ciudad VARCHAR(20),
descuento_1 INT,
descuento_2 INT
);
INSERT INTO proveedores VALUES('A001','Distribuciones Sur','956525354','Ceuta',5,10),
('A002','Todomasa SL','952875309','Malaga',3,6),
('A003','La mancha pastelera','953709912','Jaen',15,20),
('B001','Romelsa','912345762','Madrid',10,20),
('B002','Gegatur SL','933988344','Barcelona',7,13);
Cursor.sql
USE almacen;
DELIMITER $$
DROP PROCEDURE IF EXISTS art $$
CREATE PROCEDURE art()
BEGIN
DECLARE fin boolean;
DECLARE c1_codProv VARCHAR(4);
DECLARE c1_nomProv VARCHAR(30);
DECLARE c2_Articulos VARCHAR(20);
DECLARE cur_proveedor CURSOR FOR SELECT cod_prov,nombre_prov FROM proveedores;
DECLARE cur_articulos CURSOR FOR SELECT descripcion FROM articulos WHERE cod_prov=c1_codProv;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET fin=true;
SET fin=0;
OPEN cur_proveedor;
FETCH cur_proveedor INTO c1_codProv,c1_nomProv;
WHILE fin=false DO
SELECT c1_nomProv;
FETCH cur_proveedor INTO c1_codProv,c1_nomProv;
OPEN cur_articulos;
FETCH cur_articulos INTO c2_Articulos;
WHILE fin=false DO
SELECT c2_Articulos;
FETCH cur_articulos INTO c2_Articulos;
END WHILE;
SET fin = false;
CLOSE cur_Articulos;
FETCH cur_proveedor INTO c1_codProv,c1_nomProv;
END WHILE;
CLOSE cur_proveedor;
END $$
DELIMITER ;
call art();
And my cursor fails me because it does not return the expected result. For example DISTRIBUCIONES SUR should give me SUAVIZANTE, PALMERITA and ZANAHORIA.
RUN EXAMPLE
I found my bug. It turns out that I had a fetch left over and that's why it cut me off and didn't give it to me correctly because it overwrote what I had before.
The fetch that was left over is the one that is commented on
USE almacen;
DELIMITER $$
DROP PROCEDURE IF EXISTS art $$
CREATE PROCEDURE art()
BEGIN
DECLARE fin boolean DEFAULT FALSE;
DECLARE c1_codProv VARCHAR(4);
DECLARE c1_nomProv VARCHAR(30);
DECLARE c2_Articulos VARCHAR(20);
DECLARE cur_proveedor CURSOR FOR SELECT cod_prov,nombre_prov FROM proveedores;
DECLARE cur_articulos CURSOR FOR SELECT descripcion FROM articulos WHERE cod_prov=c1_codProv;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET fin=true;
OPEN cur_proveedor;
FETCH cur_proveedor INTO c1_codProv,c1_nomProv;
WHILE fin=FALSE DO
SELECT c1_nomProv;
# FETCH cur_proveedor INTO c1_codProv,c1_nomProv;
OPEN cur_articulos;
FETCH cur_articulos INTO c2_Articulos;
WHILE fin=FALSE DO
SELECT c2_Articulos;
FETCH cur_articulos INTO c2_Articulos;
END WHILE;
SET fin = FALSE;
CLOSE cur_Articulos;
FETCH cur_proveedor INTO c1_codProv,c1_nomProv;
END WHILE;
SET fin = FALSE;
CLOSE cur_proveedor;
END $$
DELIMITER ;
call art();
RUN EXAMPLE :

my procedure with cursor in mysql

I have a problem and I don't know how to solve it.
I need to create a procedure with cursor to insert into Vizite: dataora (i need a function), Medici_Idm,Pacienti_Idm,Cabinete_Idm from temporary table.My procedure doesn't work, i also use for select tables: Medici, Pacineti,Cabinete to extract id.
Table 1:
CREATE TABLE IF NOT EXISTS Vizite (
Idv INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
DataOra DATETIME,
Medici_Idm INT NOT NULL,
Pacienti_Idp INT NOT NULL,
Cabinete_Idc INT NOT NULL,
FOREIGN KEY (Medici_Idm) REFERENCES Medici(Idm),
FOREIGN KEY (Pacienti_Idp) REFERENCES Pacienti(Idp),
FOREIGN KEY (Cabinete_Idc) REFERENCES Cabinete(Idc)
) Engine=INNODB;
Table 2:
CREATE TEMPORARY TABLE IF NOT EXISTS TempVizite (
Idt INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
DataVizita VARCHAR(250),
OraIntrare TIME,
NumePacient VARCHAR(250),
PrenumePacient VARCHAR(250),
NumeMedic VARCHAR(250),
PrenumeMedic VARCHAR(250),
Cabinet VARCHAR (250));
the procedure:
DELIMITER /
CREATE PROCEDURE VARIANTA3()
BEGIN
DECLARE M_I,P_I,C_I VARCHAR(100);
DECLARE I_V INT;
DECLARE D DATE;
DECLARE O TIME;
DECLARE CURS1 CURSOR FOR -- declaram cursorul
SELECT IDT,DATAVIZITA,ORAINTRARE,NUMEMEDIC,NUMEPACIENT,CABINET FROM TEMPVIZITE;
DECLARE EXIT HANDLER FOR 1329 BEGIN END; -- declaram handler specific erorii de terminarea cursorului
OPEN CURS1;
BUCLA: LOOP
FETCH CURS1 INTO M_I,P_I,C_I,I_V,D,O;
INSERT IGNORE INTO VIZITE VALUES(I_V,#DATAORA,M_I,P_I,C_I);
SELECT TIMESTAMP(DATAVIZITA,ORAINTRARE) INTO #DATAORA;
SELECT IDM FROM MEDICI WHERE NUME = NUMEMEDIC INTO M_I;
SELECT IDP FROM PACIENTI WHERE NUME = NUMEPACIENT INTO P_I;
SELECT IDC FROM CABINETE WHERE NUME = CABIENT INTO C_I;
END LOOP;
CLOSE CURS1;
END /
DELIMITER ;

How to create stored procedure in mysql workbench?

I know Microsoft sql server and I think this codes doesn't contain an error. But Mysql thow an exeption which I Couldn't undestant. Is anybody can explain it for me and
please,give me mysql function,view,stored procedure examples website name
CREATE PROCEDURE spInsertEmployee
(
Employee_Name nvarchar(20),
Employee_Surname nvarchar(20),
Department_Name nvarchar(20)
)
BEGIN
declare Department_Id int; /*error*/
select Id into Department_Id from tblDepartment where tblDepartment.Department_Name=Department_Name;
insert into tblVeri(Employee_Name,Employee_Surname,Department_Id) values(Employee_Name,Employee_Surname,Department_Id);
END /*error*/
You must define IN for the parameters.
DELIMITER $$
CREATE PROCEDURE spInsertEmployee
(
IN Employee_Name nvarchar(20),
IN Employee_Surname nvarchar(20),
IN Department_Name nvarchar(20)
)
BEGIN
declare Department_Id INT;
select Id into Department_Id from tblDepartment WHERE tblDepartment.Department_Name=Department_Name;
insert into tblVeri(Employee_Name,Employee_Surname,Department_Id) VALUES(Employee_Name,Employee_Surname,Department_Id);
END;

how to write procedure to insert data in to the table in phpmyadmin?

I have created table as below:
student:
+----+------+-----------+--------+
|uid | name | user_name | branch |
+----+------+-----------+--------+
| | | | |
+----+------+-----------+--------+
I want to insert data in to the table using procedure.
the procedure which i wrote is:
create procedure add(in_name varchar(50),in_user_name
varchar(50),in_branch varchar(50))
begin
insert into student
(name,user_name,branch) values (in_name ,in_user_name,in_branch);
end;
Try this-
CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
insert into student (name,user_name,branch) values (name ,user_name,branch);
END
# Switch delimiter to //, so phpMyAdmin will not execute it line by line.
DELIMITER //
CREATE PROCEDURE usp_rateChapter12
(IN numRating_Chapter INT(11) UNSIGNED,
IN txtRating_Chapter VARCHAR(250),
IN chapterName VARCHAR(250),
IN addedBy VARCHAR(250)
)
BEGIN
DECLARE numRating_Chapter INT;
DECLARE txtRating_Chapter VARCHAR(250);
DECLARE chapterName1 VARCHAR(250);
DECLARE addedBy1 VARCHAR(250);
DECLARE chapterId INT;
DECLARE studentId INT;
SET chapterName1 = chapterName;
SET addedBy1 = addedBy;
SET chapterId = (SELECT chapterId
FROM chapters
WHERE chaptername = chapterName1);
SET studentId = (SELECT Id
FROM students
WHERE email = addedBy1);
SELECT chapterId;
SELECT studentId;
INSERT INTO ratechapter (rateBy, rateText, rateLevel, chapterRated)
VALUES (studentId, txtRating_Chapter, numRating_Chapter,chapterId);
END //
//DELIMITER;
This method work for me:
DELIMITER $$
DROP PROCEDURE IF EXISTS db.test $$
CREATE PROCEDURE db.test(IN id INT(12),IN NAME VARCHAR(255))
BEGIN
INSERT INTO USER VALUES(id,NAME);
END$$
DELIMITER ;