I can't find the error. can you help me?
DELIMITER $$
CREATE PROCEDURE ReadBalance (IN mes INT,IN anio INT)
BEGIN
DECLARE rowid INT;
DECLARE entity INT;
DECLARE grupo VARCHAR(100);
DECLARE relacion INT;
DECLARE ini INT;
DECLARE fin INT;
DECLARE tipo INT;
DECLARE detalle INT;
DECLARE ctain INT;
DECLARE ctaen INT;
DECLARE debe DECIMAL(17,2);
DECLARE haber DECIMAL(17,2);
DECLARE saldo DECIMAL(17,2);
DECLARE done INT DEFAULT 0;
CREATE TEMPORARY TABLE Balance (
rowid INT NOT NULL
, entity TINYINT NOT NULL DEFAULT 0
, grupo VARCHAR(150) NOT NULL
, relacion INT UNSIGNED NOT NULL DEFAULT 0
, ini INT UNSIGNED NOT NULL DEFAULT 0
, fin INT UNSIGNED NOT NULL DEFAULT 0
, tipo INT UNSIGNED NOT NULL DEFAULT 1
, detalle INT UNSIGNED NOT NULL DEFAULT 0
, ctain INT UNSIGNED NOT NULL DEFAULT 0
, ctaen INT UNSIGNED NOT NULL DEFAULT 0
, debe DECIMAL(12,2) NOT NULL DEFAULT 0.00
, haber DECIMAL(12,2) NOT NULL DEFAULT 0.00
, saldo DECIMAL(12,2) NOT NULL DEFAULT 0.00
) ENGINE=MEMORY;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
DECLARE cur1 CURSOR FOR
SELECT
g.`rowid`,
g.`entity`,
g.`grupo`,
g.`fk_codagr_rel`,
g.`fk_codagr_ini`,
g.`fk_codagr_fin`,
g.`tipo_edo_financiero`,
g.`Detalle`,
ctai.`cta`,
ctae.`cta`
FROM
`llx_contab_grupos` g
INNER JOIN `llx_contab_cat_ctas` ctai
ON ctai.`rowid` = g.`fk_codagr_ini`
INNER JOIN llx_contab_cat_ctas ctae
ON ctae.`rowid` = g.`fk_codagr_fin` ;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO rowid, entity, grupo,relacion, ini,fin,tipo,detalle,ctain,ctaen;
IF done =1THEN
LEAVE read_loop;
END IF;
SELECT debe := SUM(d.`debe`), haber:= SUM(d.`haber`) FROM `llx_contab_polizasdet` d
INNER JOIN llx_contab_polizas e ON e.`rowid` = d.`fk_poliza`
WHERE e.`anio` = anio
AND e.`mes` = mes
AND d.`cuenta` >= ctain
AND d.`cuenta` <= ctaen
;
saldo = debe-haber;
INSERT INTO Balance (
rowid,
entity,
grupo,
relacion,
ini,
fin,
tipo,
detalle,
ctain,
ctaen,
debe,
haber,
saldo
)
VALUES
(
rowid,
entity,
grupo,
relacion,
ini,
fin,
tipo,
detalle,
ctain,
ctaen,
debe,
haber,
saldo
) ;
END LOOP read_loop;
CLOSE cur1;
SELECT * FROM Balance;
END$$
DELIMITER ;
error message:
1 queries executed, 0 success, 1 errors, 0 warnings
Query:
CREATE PROCEDURE ReadBalance (IN mes INT,IN anio INT) BEGIN DECLARE rowid INT;
DECLARE entity INT;
DECLARE grupo VARCHAR(100); D...
Error 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 'DECLARE CONTINUE HANDLER FOR NOT FOUND SET done =
1;
DECLARE cur1 CURSOR FOR
SE' at line 32
Execution Time : 0 sec
Transfer Time : 0 sec
Total Time : 0 sec
I create this, and works correctly;
DELIMITER $$
USE `tindustrial`$$
DROP PROCEDURE IF EXISTS `Cur`$$
CREATE DEFINER = `root` #`localhost` PROCEDURE `Cur` ()
BEGIN
DECLARE rowid INT ;
DECLARE entity INT ;
DECLARE grupo VARCHAR (100) ;
DECLARE relacion INT ;
DECLARE ini INT ;
DECLARE fin INT ;
DECLARE tipo INT ;
DECLARE detalle INT ;
DECLARE ctain INT ;
DECLARE ctaen INT ;
DECLARE debe DECIMAL (17, 2) ;
DECLARE haber DECIMAL (17, 2) ;
DECLARE saldo DECIMAL (17, 2) ;
DECLARE no_more_rows BOOLEAN ;
DECLARE cur_B CURSOR FOR
SELECT
g.rowid,
g.entity,
g.grupo,
g.fk_codagr_rel,
g.fk_codagr_ini,
g.fk_codagr_fin,
g.tipo_edo_financiero,
g.Detalle,
ctai.cta,
ctae.cta
FROM
llx_contab_grupos g
INNER JOIN llx_contab_cat_ctas ctai
ON ctai.rowid = g.fk_codagr_ini
INNER JOIN llx_contab_cat_ctas ctae
ON ctae.rowid = g.fk_codagr_fin ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = 1 ;
CREATE TEMPORARY TABLE Balance (
rowid INT NOT NULL,
entity TINYINT NOT NULL DEFAULT 0,
grupo VARCHAR (150) NOT NULL,
relacion INT UNSIGNED NOT NULL DEFAULT 0,
ini INT UNSIGNED NOT NULL DEFAULT 0,
fin INT UNSIGNED NOT NULL DEFAULT 0,
tipo INT UNSIGNED NOT NULL DEFAULT 1,
detalle INT UNSIGNED NOT NULL DEFAULT 0,
ctain INT UNSIGNED NOT NULL DEFAULT 0,
ctaen INT UNSIGNED NOT NULL DEFAULT 0,
debe DECIMAL (12, 2) NOT NULL DEFAULT 0.0,
haber DECIMAL (12, 2) NOT NULL DEFAULT 0.0,
saldo DECIMAL (12, 2) NOT NULL DEFAULT 0.0
) ENGINE=MEMORY;
OPEN cur_b ;
the_loop :
LOOP
FETCH cur_B INTO rowid,
entity,
grupo,
relacion,
ini,
fin,
tipo,
detalle,
ctain,
ctaen ;
IF no_more_rows
THEN CLOSE cur_b ;
LEAVE the_loop ;
END IF ;
END LOOP the_loop ;
CLOSE cur_b ;
TRUNCATE TABLE Balance ;
END $$
DELIMITER ;
Related
I am trying to convert a complex oracle sql procedure to mysql. The procedure contains of many differenct selects, cursors etc. I already wrote a version of it in mysql, but it does not work and only gives some error messages. I hope on could help me.
Tables
CREATE TABLE IF NOT EXISTS `NutritionalInformation`
(
`idNuIn` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
`calories` FLOAT NULL,
`saturatedFat` FLOAT NULL,
`transFat` FLOAT NULL,
`carbohydrates` FLOAT NULL,
`sugar` FLOAT NULL,
`protein` FLOAT NULL,
`salt` FLOAT NULL
);
CREATE TABLE IF NOT EXISTS `Inventory`
(
`idInventory` INT NOT NULL,
`idIngredient` INT NOT NULL,
`idStore` INT NOT NULL,
`expiryDate` DATE NULL,
`deliveryDate` DATE NOT NULL,
`amount` INT NOT NULL,
`isAccessible` INT NOT NULL,
CONSTRAINT `fk_Inventory_Ingredient`
FOREIGN KEY (`idIngredient`)
REFERENCES `Ingredient` (`idIngredient`),
CONSTRAINT `fk_Inventory_StoreA`
FOREIGN KEY (`idStore`)
REFERENCES `WaffleStore` (`idStore`),
CONSTRAINT pk_Inventory
PRIMARY KEY (idInventory)
);
CREATE TABLE IF NOT EXISTS `Inventory`
(
`idInventory` INT NOT NULL,
`idIngredient` INT NOT NULL,
`idStore` INT NOT NULL,
`expiryDate` DATE NULL,
`deliveryDate` DATE NOT NULL,
`amount` INT NOT NULL,
`isAccessible` INT NOT NULL,
PRIMARY KEY (`idIngredient`, `idStore`),
CONSTRAINT `fk_Inventory_Ingredient`
FOREIGN KEY (`idIngredient`)
REFERENCES `Ingredient` (`idIngredient`),
CONSTRAINT `fk_Inventory_StoreA`
FOREIGN KEY (`idStore`)
REFERENCES `WaffleStore` (`idStore`)
);
CREATE TABLE IF NOT EXISTS `Product`
(
`idProduct` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
`idNuIn` INT NOT NULL,
`price` FLOAT NOT NULL,
`name` VARCHAR(255) NOT NULL,
CONSTRAINT `fk_Product_NutritionalInformation1`
FOREIGN KEY (`idNuIn`)
REFERENCES `NutritionalInformation` (`idNuIn`)
);
CREATE TABLE IF NOT EXISTS `Waffle`
(
`idWaffle` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
`creatorName` VARCHAR(255) NULL,
`creationDate` DATE NOT NULL,
`processingTimeSec` INT,
`healty` VARCHAR(255),
CONSTRAINT `fk_Waffle_Product1`
FOREIGN KEY (`idWaffle`)
REFERENCES `Product` (`idProduct`)
);
CREATE TABLE IF NOT EXISTS `WaffleIngredient`
(
`idIngredient` INT NOT NULL,
`idWaffle` INT NOT NULL,
`amount` INT NOT NULL,
PRIMARY KEY (`idIngredient`, `idWaffle`),
CONSTRAINT `fk_WaffleRecept_Ingredient1`
FOREIGN KEY (`idIngredient`)
REFERENCES `Ingredient` (`idIngredient`),
CONSTRAINT `fk_WaffleRecept_Waffle1`
FOREIGN KEY (`idWaffle`)
REFERENCES `Waffle` (`idWaffle`)
);
CREATE TABLE IF NOT EXISTS `WaffleStore`
(
`idStore` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(255) NULL,
`areaCode` VARCHAR(15) NULL,
`location` VARCHAR(255) NULL,
`streetName` VARCHAR(255) NULL,
`houseNumber` VARCHAR(45) NULL
);
Example Inserts
INSERT INTO NutritionalInformation (idNuIn, calories, saturatedFat, transFat, carbohydrates, sugar, protein, salt)
VALUES (4, 60, 0, 0, 0, 0, 0, 0);
INSERT INTO NutritionalInformation (idNuIn, calories, saturatedFat, transFat, carbohydrates, sugar, protein, salt)
VALUES (5, 350, 3, 3, 5, 5, 3, 1);
INSERT INTO INGREDIENT (idIngredient, idNuIn, name, unit, price, processingTimeSec)
VALUES (3, 4, 'Apfel', 'g', 0.5, 3);
INSERT INTO PRODUCT (idProduct, idNuIn, price, name)
VALUES (4, 5, 3.5, 'ApfelWaffel');
INSERT INTO WAFFLE (idWaffle, creatorName, creationDate, processingTimeSec, healty)
VALUES (4, 'Berndt', '2020-12-01', NULL, NULL);
INSERT INTO WAFFLEINGREDIENT(idIngredient, idWaffle, amount)
VALUES (3, 4, 2);
INSERT INTO WaffleStore (idStore, name, areaCode, location, streetName, houseNumber)
VALUES (1, 'Waffle GMBH', '50000', 'TEST', 'TEST', '38');
INSERT INTO INVENTORY(idInventory, idIngredient, idStore, expiryDate, deliveryDate, amount, isAccessible)
VALUES (2, 3, 1, '3032-12-30', '3032-12-30', 100, 1);
INSERT INTO WaffleOrder(idOrder, idStore, totalAmount, paymentStatus, orderDate)
VALUES (1, 1, 2, 0, '2020-12-30');
Oracle SQL PROCEDURE
CREATE OR REPLACE PROCEDURE OnInventoryAdd (
s_idProduct IN INT,
s_idOrder IN INT,
s_extenal_amount IN INT
)
IS
v_store INT;
v_waffle_id INT;
v_cursor_ingredientid INT;
v_cursor_amount INT;
v_cursor_expiryDate DATE;
v_cursor_deliveryDate DATE;
v_operator VARCHAR(3) := 'add';
CURSOR v_Ingredient_Cursor_On_Insert(w_Id INT) IS
SELECT idIngredient, amount FROM WAFFLEINGREDIENT WHERE idWaffle = w_Id;
CURSOR v_Ingredient_Cursor_On_Delete(i_id INT) IS
SELECT expiryDate, deliveryDate FROM Inventory WHERE idIngredient = i_id;
BEGIN
SELECT idStore INTO v_store FROM WAFFLEORDER WHERE idOrder = s_idOrder;
SELECT w.idWaffle INTO v_waffle_id FROM Waffle w WHERE w.idProduct = s_idProduct;
-- If more than one waffle is bought
FOR x IN 1..s_extenal_amount LOOP
-- Get all ingredient information of waffle
OPEN v_Ingredient_Cursor_On_Insert(v_waffle_id);
LOOP
FETCH v_Ingredient_Cursor_On_Insert INTO v_cursor_ingredientId, v_cursor_amount;
EXIT WHEN v_Ingredient_Cursor_On_Insert%NOTFOUND;
-- Get all old expirydate and deliverydate information
OPEN v_Ingredient_Cursor_On_Delete(v_cursor_ingredientId);
LOOP
FETCH v_Ingredient_Cursor_On_Delete INTO v_cursor_expiryDate, v_cursor_deliveryDate;
EXIT WHEN v_Ingredient_Cursor_On_Delete%NOTFOUND;
END LOOP;
CLOSE v_Ingredient_Cursor_On_Delete;
END LOOP;
CLOSE v_Ingredient_Cursor_On_Insert;
-- Update the Inventory
InventoryUpdate(v_store, v_cursor_ingredientId, v_cursor_amount, v_operator, v_cursor_expiryDate, v_cursor_deliveryDate);
END LOOP;
END;
/
Current Version
DROP PROCEDURE IF EXISTS `OnInventoryAdd`;
DELIMITER //
CREATE PROCEDURE `OnInventoryAdd` (
s_idProduct INT,
s_idOrder INT,
s_extenal_amount INT
)
BEGIN
DECLARE loop_counter INT DEFAULT s_extenal_amount;
DECLARE v_store INT;
DECLARE v_waffle_id INT;
DECLARE v_cursor_ingredientid INT;
DECLARE v_cursor_amount INT;
DECLARE v_cursor_expiryDate DATE;
DECLARE v_cursor_deliveryDate DATE;
DECLARE v_operator VARCHAR(3) DEFAULT 'add';
DECLARE v_c_insert_done, v_c_delete_done BOOLEAN DEFAULT FALSE;
DECLARE v_Ingredient_Cursor_On_Insert CURSOR FOR
SELECT idIngredient, amount FROM WAFFLEINGREDIENT WHERE idWaffle = v_waffle_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_c_insert_done = TRUE;
SELECT idStore INTO v_store FROM WAFFLEORDER WHERE idOrder = s_idOrder;
SELECT idWaffle INTO v_waffle_id FROM Waffle WHERE idWaffle = s_idProduct;
WHILE loop_counter > 0 DO
SET loop_counter = loop_counter - 1;
OPEN v_Ingredient_Cursor_On_Insert;
curr_insert_loop: LOOP
FETCH FROM v_Ingredient_Cursor_On_Insert INTO v_cursor_ingredientId, v_cursor_amount;
IF v_c_insert_done THEN
CLOSE v_Ingredient_Cursor_On_Insert;
LEAVE curr_insert_loop;
END IF;
BLOCK2 : BEGIN
DECLARE v_Ingredient_Cursor_On_Delete CURSOR FOR
SELECT expiryDate, deliveryDate FROM Inventory WHERE idIngredient = v_cursor_ingredientid;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_c_delete_done = TRUE;
OPEN v_Ingredient_Cursor_On_Delete;
curr_delete_loop : LOOP
FETCH FROM v_Ingredient_Cursor_On_Delete INTO v_cursor_expiryDate, v_cursor_deliveryDate;
IF v_c_delete_done THEN
CLOSE v_Ingredient_Cursor_On_Delete;
LEAVE curr_delete_loop;
END IF;
END LOOP curr_delete_loop;
END BLOCK2;
END LOOP curr_insert_loop;
CALL InventoryUpdate(v_store, v_cursor_ingredientId, v_cursor_amount, v_operator, v_cursor_expiryDate, v_cursor_deliveryDate);
END WHILE;
END //
DELIMITER ;
Error
4 row(s) affected, 2 warning(s): 1264 Out of range value for column 'expiryDateOnInsert' at row 2 1264 Out of range value for column 'deliveryDateOnInsert' at row 1
Even tho I wrote the Oracle Procedure, I have zero clue how to write the same behavior in MYSQL and more over how to fix this error. If there is a alternative to do the same without cursors, then it would be fine too
Ok, I've managed to convert the oracle procedure into mysql stored procedure, here is the working code:
Code
CREATE PROCEDURE `OnInventoryAdd` (
s_idProduct INT,
s_idOrder INT,
s_extenal_amount INT
)
BEGIN
DECLARE loop_counter INT DEFAULT s_extenal_amount;
DECLARE done1, done2 BOOLEAN DEFAULT FALSE;
DECLARE v_store INT;
DECLARE v_waffle_id INT;
DECLARE v_operator VARCHAR(3) DEFAULT 'add';
DECLARE v_cursor_ingredientid INT;
DECLARE v_cursor_amount INT;
DECLARE v_cursor_expiryDate DATE;
DECLARE v_cursor_deliveryDate DATE;
DECLARE v_Ingredient_Cursor_On_Insert CURSOR FOR
SELECT idIngredient, amount FROM WAFFLEINGREDIENT WHERE idWaffle = v_waffle_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done1 = TRUE;
SELECT idStore INTO v_store FROM WAFFLEORDER WHERE idOrder = s_idOrder;
SELECT idWaffle INTO v_waffle_id FROM Waffle WHERE idWaffle = s_idProduct;
REPEAT
OPEN v_Ingredient_Cursor_On_Insert;
loop1 : LOOP
FETCH FROM v_Ingredient_Cursor_On_Insert INTO v_cursor_ingredientId, v_cursor_amount;
IF done1 THEN
CLOSE v_Ingredient_Cursor_On_Insert;
LEAVE loop1;
END IF;
BLOCK1 : BEGIN
DECLARE v_Ingredient_Cursor_On_Delete CURSOR FOR
SELECT expiryDate, deliveryDate FROM Inventory WHERE idIngredient = v_cursor_ingredientid;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done2 = TRUE;
OPEN v_Ingredient_Cursor_On_Delete;
loop2 : LOOP
FETCH FROM v_Ingredient_Cursor_On_Delete INTO v_cursor_expiryDate, v_cursor_deliveryDate;
IF done2 THEN
SET done2 = FALSE; -- This was the solution
LEAVE loop2;
END IF;
END LOOP loop2;
END BLOCK1;
END LOOP loop1;
CALL InventoryUpdate(v_store, v_cursor_ingredientId, v_cursor_amount, v_operator, v_cursor_expiryDate, v_cursor_deliveryDate);
SET loop_counter = loop_counter - 1;
UNTIL loop_counter = 0
END REPEAT;
END //
DELIMITER ;
similar to StackOverflowPosting I would like to calculate the Levenshtein Distance for a m x n matrix consisting of TITLE1 and TITLE2.
My Levenshtein Functions works fine and is from here: LD
But my Question is how can I loop through the m x n in a UDF?
The Result should be a table with m x n rows with LD, TITLE1 and TITLE2.
I have done this - BUT I ALWAYS GET AN ERROR
1338 Cursor Declaration after Handler Declaration
My UDF looks like this:
BEGIN
DECLARE bDone INT;
DECLARE bDone1 INT;
DECLARE var2 varCHAR(255); -- or approriate type
DECLARE Var1 INT;
DECLARE c1Var1 VARCHAR(250);
DECLARE curs CURSOR FOR SELECT recid as BIOTIrecid, replace(replace(BIOGRAPHYTITLE," [in SCOPUS]",""),"[SIMILAR]","") as bioti FROM BIO ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
DECLARE curs1 CURSOR FOR SELECT trim(concat(scopus.Titel," ",scopus.Untertitel)) as scopusti FROM scopus ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
DROP TABLE IF EXISTS LDResults;
CREATE TABLE `LDResults` (
`BIOGRAPHYTITLE` varchar(255) DEFAULT NULL,
`recid` int(11) NOT NULL AUTO_INCREMENT,
`BIOTIrecid` int(11) default NULL,
`LD` varchar(255) DEFAULT NULL,
`ScopusTI` varchar(255) DEFAULT NULL,
PRIMARY KEY (`recid`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
OPEN curs1;
SET bDone1 = 0;
#---------------- run all rows for scopusti
REPEAT
FETCH curs1 into c1var1;
#-----------------------------------------
OPEN curs;
SET bDone = 0;
#----- run all COLUMNs for biographytitle
REPEAT
FETCH curs INTO var1, var2;
INSERT INTO LDResults (`BIOGRAPHYTITLE`, `BIOTIrecid`, `LD`, `ScopusTI`) VALUES (var2, var1, LEVENSHTEIN(var2,c1var1), c1var1);
UNTIL bDone END REPEAT;
#--------------------------------------------
CLOSE curs;
UNTIL bDone1 END REPEAT;
CLOSE curs1;
SELECT * FROM LDResults;
END
Is my way to solve this problem sophisticated or could this be done on a more faster and better solution ?
Thanks for all advices.
EDIT:
I could make it with a counter here: Any comments?
BEGIN
-- DECLARE bDone INT;
-- DECLARE bDone1 INT;
DECLARE i INT;
DECLARE var2 varCHAR(255); -- or approriate type
DECLARE Var1 INT;
DECLARE cVar1 VARCHAR(250);
DECLARE curs1 CURSOR FOR SELECT trim(concat(t.Titel," ",t.Untertitel)) as scopusti FROM tscopus t ;
DECLARE curs CURSOR FOR SELECT recid as BIOTIrecid, replace(replace(BIOGRAPHYTITLE," [in SCOPUS]",""),"[SIMILAR]","") as bioti FROM tBIO ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
#DECLARE curs1 CURSOR FOR SELECT trim(concat(t.Titel," ",t.Untertitel)) as scopusti FROM tscopus t ;
#DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
DROP TABLE IF EXISTS LDResults;
CREATE TABLE `LDResults` (
`BIOGRAPHYTITLE` varchar(255) DEFAULT NULL,
`recid` int(11) NOT NULL AUTO_INCREMENT,
`BIOTIrecid` int(11) default NULL,
`LD` varchar(255) DEFAULT NULL,
`ScopusTI` varchar(255) DEFAULT NULL,
PRIMARY KEY (`recid`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
OPEN curs1;
SET i = 0;
SET bDone1 = 0;
-- ---------------- run all rows for scopusti
REPEAT
FETCH curs1 into cvar1;
set i=(i+1);
-- -----------------------------------------
OPEN curs;
SET bDone = 0;
-- ----- run all COLUMNs for biographytitle
REPEAT
FETCH curs INTO var1, var2;
INSERT INTO LDResults (`BIOGRAPHYTITLE`, `BIOTIrecid`, `LD`, `ScopusTI`) VALUES (var2, var1, LEVENSHTEIN(var2,cvar1), cvar1);
UNTIL bDone END REPEAT;
-- --------------------------------------------
CLOSE curs;
UNTIL (i >= 2) END REPEAT;
CLOSE curs1;
SELECT * FROM LDResults;
END
I mean you can do it by next way useng CROSS JOIN without loops in your code. CROSS JOIN by definition return product of two tables rows result.
So you can use this result and after some data manipulation insert the result into new table like:
DROP TABLE IF EXISTS LDResults;
CREATE TABLE `LDResults` (
`BIOGRAPHYTITLE` varchar(255) DEFAULT NULL,
`recid` int(11) NOT NULL AUTO_INCREMENT,
`BIOTIrecid` int(11) default NULL,
`LD` varchar(255) DEFAULT NULL,
`ScopusTI` varchar(255) DEFAULT NULL,
PRIMARY KEY (`recid`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
INSERT INTO LDResults (`BIOGRAPHYTITLE`, `BIOTIrecid`, `LD`, `ScopusTI`)
SELECT bioti, BIOTIrecid, LEVENSHTEIN(bioti,scopusti), scopusti
FROM (
SELECT
replace(replace(BIO.BIOGRAPHYTITLE," [in SCOPUS]",""),"[SIMILAR]","") as bioti,
BIO.recid as BIOTIrecid,
trim(concat(scopus.Titel," ",scopus.Untertitel)) as scopusti
FROM scopus
CROSS JOIN BIO
) tbl;
I am Trying to create stored procedure in MYSQLand getting below error.
I googled about it but no solution found please help me in this.
DELIMITER //
CREATE OR REPLACE PROCEDURE P_PROCESS_USER_STG ( OUT O_error_msg VARCHAR(3000),
OUT O_status VARCHAR(300),
IN I_uploaded_by INT (10))
BEGIN
declare L_program_name VARCHAR(100);
declare L_login_id INT(10) ;
declare L_password VARCHAR(100);
declare L_first_name VARCHAR(100);
declare L_last_name VARCHAR(100);
declare L_privilege_group_id INT(10) ;
declare L_group_id INT(10) ;
declare L_message VARCHAR(100);
declare L_date_of_upload TIMESTAMP ;
declare L_date_of_update TIMESTAMP ;
declare L_uploaded_by INT(10) ;
declare L_status VARCHAR(10) ;
declare L_error_msg VARCHAR(100),
declare L_finished INT(1) DEFAULT 0;
declare C_user_stg CURSOR FOR
SELECT LOGIN_ID,
PASSWORD,
FIRST_NAME,
LAST_NAME,
PRIVILEGE_GROUP_ID,
GROUP_ID
FROM uploaded_user_stg
where UPLOADED_BY = I_uploaded_by
and status in ( 'NEW' , 'UPDATE' );
declare CONTINUE HANDLER
FOR NOT FOUND SET L_finished = 1;
OPEN C_user_stg;
get_user: LOOP
FETCH C_user_stg INTO L_login_id ,
L_password ,
L_first_name ,
L_last_name ,
L_privilege_group_id,
L_group_id ;
IF L_finished = 1 THEN
LEAVE get_user;
END IF;
-- build email list
CALL P_CREATE_USER ( L_message ,
L_status ,
L_login_id ,
L_password ,
L_first_name,
L_last_name ,
L_privilege_group_id,
L_group_id )
UPDATE uploaded_user_stg
SET status = L_status,
error_msg = L_message
date_of_update = now();
where login_id = L_login_id;
END LOOP get_email;
CLOSE get_user;
END//
DELIMITER ;
I am getting Below error :
ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that on for the right syntax to use near '
declare L_finished INT(1) DEFAULT 0;
declare C_' at line 18
Change this from:
declare L_error_msg VARCHAR(100),
to
declare L_error_msg VARCHAR(100);
I'm experiencing a 'Column cannot be null' error for 2 columns, when I try to run a SP.
Source table A is defined as below:
CREATE TABLE `test_data`.`offer` (
`id` INT NOT NULL,
`hotel_id` INT NOT NULL,
`currency_id` INT NOT NULL,
`source_system_code` VARCHAR(64) NOT NULL,
`available_cnt` INT NOT NULL,
`sellings_price` FLOAT NOT NULL,
`checkin_date` DATE NOT NULL,
`checkout_date` DATE NOT NULL,
`valid_offer_flag` TINYINT(1) NOT NULL,
`offer_valid_from` DATETIME NOT NULL,
`offer_valid_to` DATETIME NOT NULL,
`breakfast_included_flag` TINYINT(1) NOT NULL,
`insert_datetime` DATETIME NOT NULL,
PRIMARY KEY (`id`));
Table B into which I am inserting the data:
CREATE TABLE `calculate_USD` (
`counter` int(11) NOT NULL AUTO_INCREMENT,
`dates` date DEFAULT NULL,
`id` int(11) NOT NULL,
`hotel_id` int(11) NOT NULL,
`original_price` int(11) NOT NULL,
`currency_id` int(11) NOT NULL,
PRIMARY KEY (`counter`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Here is the SP for the insertion:
CREATE PROCEDURE `test_procedure`()
BEGIN
DECLARE aid INT;
DECLARE avalid_from_date DATE;
DECLARE avalid_to_date DATE;
DECLARE hotel_id INT;
DECLARE original_price float;
DECLARE currency_id int;
DECLARE tempdt DATE;
DECLARE done INT DEFAULT FALSE;
DECLARE getdates CURSOR FOR
SELECT id,offer_valid_from,offer_valid_to,hotel_id,sellings_price,currency_id
from offer;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN getdates;
read_loop: LOOP
FETCH getdates
INTO aid,avalid_from_date,avalid_to_date,hotel_id,original_price,currency_id;
IF done THEN
LEAVE read_loop;
END IF;
set tempdt=date(avalid_from_date);
WHILE (tempdt <= date(avalid_to_date)) do
insert into calculate_USD(dates,id,hotel_id,original_price,currency_id)
values(tempdt,aid,hotel_id,original_price,currency_id);
set tempdt=tempdt+INTERVAL 1 DAY;
end while;
END LOOP;
CLOSE getdates;
END
//
When I call the SP,
hotel_id & currency_id columns are instigating the error code.
If I assign them both NULL default values, the SP runs however, the hotel_id & currency_id values being inserted are all NULL like so (rest are OK):
counter | dates | id | hotel_id | original_price | currency_id |
1 | 2015-4-30 | 342523| NULL | 200 | NULL |
2 | 2015-4-30 | 342524| NULL | 112 | NULL |
This is strange, because both have valid data in the source table.
Please advise.
One option that can solve is:
.
.
.
DECLARE `getdates` CURSOR FOR
SELECT
`id`,
`offer_valid_from`,
`offer_valid_to`,
-- `hotel_id`,
`offer`.`hotel_id`,
`sellings_price`,
-- `currency_id`
`offer`.`currency_id`
FROM
`offer`;
.
.
.
So I figured it out.
All I had to do was re-name the hotel_id & currency_id variables in the SP to something else and it worked.
Updated SP:
delimiter //
CREATE PROCEDURE `test_procedure`()
BEGIN
DECLARE aid INT;
DECLARE avalid_from_date DATE;
DECLARE avalid_to_date DATE;
DECLARE sp_hotel_id INT;
DECLARE original_price float;
DECLARE sp_currency_id int;
DECLARE tempdt DATE;
DECLARE done INT DEFAULT FALSE;
DECLARE getdates CURSOR FOR
SELECT id,offer_valid_from,offer_valid_to,hotel_id,sellings_price,currency_id
from offer;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN getdates;
read_loop: LOOP
FETCH getdates
INTO aid,avalid_from_date,avalid_to_date,sp_hotel_id,original_price,sp_currency_id;
IF done THEN
LEAVE read_loop;
END IF;
set tempdt=date(avalid_from_date);
WHILE (tempdt <= date(avalid_to_date)) do
insert into calculate_USD(dates,id,hotel_id,original_price,currency_id)
values(tempdt,aid,sp_hotel_id,original_price,sp_currency_id);
set tempdt=tempdt+INTERVAL 1 DAY;
end while;
END LOOP;
CLOSE getdates;
END
//
call test_procedure();
I am trying to create a transaction procedure in MySQL and I keep receiving the following syntax error which is occurring in my variable declarations:
ERROR 1064(42000): 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 ';
DECLARE emp_duplicate INT DEFAULT 0;
DECLARE old_empnum INT DEFAULT 0;
DECL' at line 6
Below is my procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS new_employee$$
CREATE PROCEDURE new_employee(in_Fname VARCHAR(15),in_Lname VARCHAR(15),
in_hire DATE, in_DOB DATE, in_sal Numeric(7,2))
BEGIN
DECLARE out_message VARCHAR;
DECLARE emp_duplicate INT DEFAULT 0;
DECLARE old_empnum INT DEFAULT 0;
DECLARE out_empnum INT DEFAULT 0;
DECLARE time_created DATETIME;
DECLARE user_var VARCHAR;
DECLARE age_var Int DEFAULT 0;
START TRANSACTION;
Select MAX(Empno)
Into old_empnum
From emp;
Select COUNT(*)
Into emp_duplicate
From emp
Where (in_Fname=Fname AND in_Lname=Lname AND in_hire=HireDate AND in_DOB=DOB);
IF emp_duplicate=0 THEN
SET out_message = 'New employee update successful';
SET out_empnum = old_empnum + 1;
SET time_created = CURRENT_TIMESTAMP();
SET user_var = USER();
SET age_var = DATEDIFF(CURRENT_DATE,in_DOB);
INSERT INTO emp(Empno,Fname,Lname,HireDate,DOB,SAL)
VALUES(in_Fname,in_Lname,in_hire,in_DOB,in_sal);
INSERT INTO log(Empno,DateCreated,Who)
VALUES(out_empnum,time_created,user_var);
SELECT out_message;
SELECT Empno, Fname, Lname, DATEDIFF(CURRENT_DATE,DOB), HireDate
From emp;
ELSE
SET out_message = 'Employee already exists';
SELECT out_message;
END IF;
COMMIT;
END$$
DELIMITER ;
I am using cmd and notepad to execute my code (just in case that's helpful). For the life of me, I cannot see the error with my declarations?????
you need to define the VARCHAR size like this
DECLARE out_message VARCHAR(20);
try this
BEGIN
DECLARE out_message VARCHAR(20); // // varchar size here
DECLARE emp_duplicate INT DEFAULT 0;
DECLARE old_empnum INT DEFAULT 0;
DECLARE out_empnum INT DEFAULT 0;
DECLARE time_created DATETIME;
DECLARE user_var VARCHAR(20); // varchar size here
DECLARE age_var Int DEFAULT 0;
you forget to datatype size for DECLARE out_message VARCHAR (30) and DECLARE user_var VARCHAR(30);
DECLARE out_message VARCHAR (30); <------------- here
DECLARE emp_duplicate INT DEFAULT 0;
DECLARE old_empnum INT DEFAULT 0;
DECLARE out_empnum INT DEFAULT 0;
DECLARE time_created DATETIME;
DECLARE user_var VARCHAR(30); <------------- here
DECLARE age_var Int DEFAULT 0;
In insert statement you are missing value for Empno
INSERT INTO emp(Empno,Fname,Lname,HireDate,DOB,SAL)
VALUES(in_Fname,in_Lname,in_hire,in_DOB,in_sal);