Following is the definition for Patients table:
Patients table Columns:
PatientId int AI PK
FirstName longtext
LastName longtext
Email longtext
NIC longtext
Phone longtext
Address longtext
City longtext
Country longtext
DOB datetime(6)
Gender longtext
Reference longtext
SerialNumberYear smallint
SerialNumber int
DoctorId int
CreatedOn datetime(6)
UpdatedOn datetime(6)
CreatedBy longtext
SMS_Allowed tinyint(1)
Email_Allowed tinyint(1)
SpecialConcern1 longtext
SpecialConcern2 longtext
SpecialConcern3 longtext
SpecialConcern4 longtext
CustomYearlyId longtext
YearlyId int
I have the following trigger in MySQL on this table:
CREATE TRIGGER generate_yearly_id BEFORE INSERT ON clinic.patients
FOR EACH ROW
BEGIN
DECLARE last_id INTEGER default 10;
DECLARE current_year DATE;
DECLARE yearly_id INTEGER default 0;
IF NEW.CustomYearlyId IS NULL THEN
BEGIN
INSERT INTO DEBUG VALUES (null,"start trigger");
#SET #last_id := (SELECT max(yearlyid) FROM patients WHERE
# YEAR(createdon)=YEAR(CURDATE()));
IF last_id IS NOT NULL THEN
BEGIN
SET #yearly_id = 1;
INSERT INTO DEBUG VALUES (null, concat("in if lastid is not null ",#yearly_id));
END;
ELSE
BEGIN
#SET #yearly_id := 1;
END;
END IF;
SET NEW.yearlyid := #yearly_id;
END;
END IF;
END;//
delimiter ;
The statement SET #yearly_id = 1; works fine. But if I change it to SET #yearly_id = #last_id;, the trigger fails. What am I doing wrong in making this assignment? last_id has a default value, so do I need to initialize it?
The following code works perfectly. Differences are 1. Variables have been initialized before being used. Apparently default value is not enough. 1. Count has been used in the "if" condition instead of testing for "is null".
CREATE TRIGGER generate_yearly_id BEFORE INSERT ON clinic.patients
FOR EACH ROW
BEGIN
DECLARE last_id INTEGER default 0;
DECLARE current_year DATE;
DECLARE yearly_id INTEGER default 1;
declare count INTEGER default 0;
IF NEW.CustomYearlyId IS NULL THEN
BEGIN
#init last_id to some value before using
SET #last_id = 0;
SET #yearly_id = 0;
#INSERT INTO DEBUG VALUES (null,"start trigger");
set #count := (select count(*) from patients where
YEAR(CreatedOn)=YEAR(curdate()));
IF #count > 0 THEN
BEGIN
SET #last_id := (SELECT max(yearlyid) FROM patients WHERE
YEAR(createdon)=YEAR(CURDATE()));
SET #yearly_id = #last_id + 1;
SET NEW.yearlyid := #yearly_id;
#INSERT INTO DEBUG VALUES (null, concat("in if lastid is not null ",#yearly_id));
END;
ELSE
BEGIN
#INSERT INTO DEBUG VALUES (null, concat("in else ",#yearly_id));
#SET #yearly_id = 1;
SET NEW.yearlyid := 1;
END;
END IF;
#Set NEW.yearlyid := 1;
END;
END IF;
END;//
delimiter ;
DELIMITER //
CREATE PROCEDURE PROCEDURE_NM ( IN PARAM_A VARCHAR(16)
, IN PARAM_B VARCHAR(16) )
BEGIN
DECLARE SRCH_CNTE VARCHAR(500) DEFAULT IN PARAM_A + PARAM_B;
DECLARE SQL_NM VARCHAR(500) DEFAULT 'PROCEDURE_NM';
DECLARE ERROR_YN VARCHAR(1) DEFAULT 'N';
DECLARE ERROR_MSG VARCHAR(500) DEFAULT NULL;
BEGIN
CALL PROC_LOG(SRCH_CNTE, SQL_NM, ERROR_YN, ERROR_MSG);
END;
BEGIN
--SOMETHING
END;
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1
ERROR_MSG = MESSAGE_TEXT;
ERROR_YN = 'Y';
CALL PROC_LOG(SRCH_CNTE, SQL_NM, ERROR_YN, ERROR_MSG);
END;
END;
END//
DELIMITER ;
"ERROR_YN" is not valid at this position, expecting an identifier.
syntax error occurs.
I have completed the variable declaration, and I don't think there's anything missing.
What should I fix?
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1 someVarient=RETURNED_SQLSTATE
, ERROR_MSG = MESSAGE_TEXT;
CALL PROC_LOG(SRCH_CNTE, SQL_NM, 'Y', ERROR_MSG);
END;
END;
It was successfully committed after changing to the code above.
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);
DELIMITER $$
USE `g4winners2`$$
DROP PROCEDURE IF EXISTS `wagerMigration`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `wagerMigration`()
BEGIN
DECLARE tbrace_done, tbrunner_done BOOLEAN DEFAULT FALSE;
DECLARE race_card_id INT(10);
DECLARE race_number INT(10);
DECLARE day_evening VARCHAR(10) ;
DECLARE locale_type VARCHAR(50) ;
DECLARE course_surface VARCHAR(8) ;
DECLARE distance_unit VARCHAR(8) ;
DECLARE race_type VARCHAR(50) ;
DECLARE sex_restriction VARCHAR(8) ;
DECLARE age_restriction VARCHAR(8) ;
DECLARE purse_usa DECIMAL(18,2) ;
DECLARE maximum_claim_price DECIMAL(9,2) ;
DECLARE race_name VARCHAR(120) ;
DECLARE race_condition VARCHAR(255) ;
DECLARE condition_text TEXT ;
DECLARE post_time TIME ;
DECLARE race_date TIMESTAMP;
DECLARE is_active TINYINT(1) ;
DECLARE race_status_type INT(11) ;
DECLARE gait VARCHAR(50) ;
DECLARE field_size SMALLINT(6);
DECLARE weather VARCHAR(25);
DECLARE comments VARCHAR(128);
DECLARE odds_updated DATETIME;
DECLARE pools_updated DATETIME;
DECLARE win_pool_total INT(11);
DECLARE plc_pool_total INT(11);
DECLARE shw_pool_total INT(11);
declare horse_name varchar(50);
declare foaling_area char(3);
declare color varchar(255);
declare sex varchar(255);
declare breeder_name varchar(255);
declare sire_name varchar(255);
declare post_position int(10);
declare program_number varchar(255);
declare weight_carried int(10);
declare scratch_indicator varchar(255);
declare trainer_first_name varchar(255);
declare owner_name varchar(255) ;
declare jockey_first_name varchar(255);
declare odds varchar(255) ;
declare owner_silks varchar(255);
declare live_odds varchar(255);
declare is_visible tinyint(10);
declare finish_position smallint(6);
declare dead_heat_flag smallint(6);
declare distance_from_winner smallint(6);
declare win_pool int(11);
declare plc_pool int(11);
declare shw_pool int(11);
DECLARE curRace CURSOR FOR SELECT ee.event_number,"wer",'en_us',ee.surface,ee.distance,ee.race_type_text,ee.sex_restriction ,ee.age_restriction,
ee.purse,ee.max_claiming_price,ee.event_name,ee.race_conditions1,ee.track_conditions,ee.post_time,ee.raceday,ee.confirmed_flag,ee.status,ee.gait,
ee.field_size,ee.weather,ee.comments,ee.odds_updated,ee.pools_updated,ee.win_pool_total,ee.plc_pool_total,ee.shw_pool_total
FROM ebet.events ee ,ebet.race_meetings trc
WHERE trc.meeting_number=ee.meeting_number
AND trc.raceday=ee.raceday;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET tbrace_done = TRUE;
OPEN curRace;
cur_race_loop: LOOP
FETCH FROM curRace INTO race_number ,day_evening ,locale_type,course_surface,distance_unit,race_type,sex_restriction ,age_restriction
,purse_usa ,maximum_claim_price ,race_name ,race_condition ,condition_text
,post_time ,race_date ,is_active ,race_status_type ,gait
,field_size,weather,comments,odds_updated,pools_updated,win_pool_total,plc_pool_total,shw_pool_total;
IF tbrace_done THEN
CLOSE curRace;
LEAVE cur_race_loop;
END IF;
SET FOREIGN_KEY_CHECKS=0;
INSERT INTO g4winners2.tb_races(race_number ,day_evening ,locale_type,course_surface,distance_unit,race_type,sex_restriction ,age_restriction
,purse_usa ,maximum_claim_price ,race_name ,race_condition ,condition_text
,post_time ,race_date ,is_active ,race_status_type ,gait
,field_size,weather,comments,odds_updated,pools_updated,win_pool_total,plc_pool_total,shw_pool_total)
VALUES (race_number ,day_evening ,locale_type,course_surface,distance_unit,race_type,sex_restriction ,age_restriction
,purse_usa ,maximum_claim_price ,race_name ,race_condition ,condition_text
,post_time ,race_date ,is_active ,race_status_type ,gait
,field_size,weather,comments,odds_updated,pools_updated,win_pool_total,plc_pool_total,shw_pool_total);
SET FOREIGN_KEY_CHECKS=1;
SET #ID:=(SELECT LAST_INSERT_ID());
SELECT CONCAT ("Result :**", #ID, " ") AS '';
SET FOREIGN_KEY_CHECKS=0;
BLOCK2: BEGIN
DECLARE curRunner CURSOR FOR SELECT er.runner_name,er.area_foaled,er.color,er.sex,er.breeder,er.sire,er.post_position,er.program_number ,er.weight,
er.scratched_flag,er.trainer,er.owner,er.jockey,er.morning_line_odds,er.silks,er.current_odds,'1', er.finish_position,er.dead_heat_flag
,er.distance_from_winner,er.win_pool,er.plc_pool,er.shw_pool FROM ebet.runners er ,ebet.events ee
WHERE
ee.meeting_number=er.meeting_number
AND ee.event_number=er.event_number
AND ee.raceday=er.raceday;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET tbrunner_done = TRUE;
OPEN curRunner;
cur_runner_loop: LOOP
FETCH curRunner INTO horse_name,foaling_area,color,sex,breeder_name,sire_name,post_position,program_number,weight_carried,scratch_indicator,trainer_first_name,owner_name,jockey_first_name,odds,owner_silks,live_odds,is_visible,finish_position,dead_heat_flag,distance_from_winner,win_pool,plc_pool,shw_pool;
IF tbrace_done THEN
set tbrace_done = false;
CLOSE curRunner;
LEAVE cur_runner_loop;
END IF;
INSERT INTO g4winners2.tb_race_runners(race_id,horse_name,foaling_area,color,sex,breeder_name,sire_name,post_position,program_number ,
weight_carried,scratch_indicator ,trainer_first_name ,owner_name ,jockey_first_name,odds ,owner_silks ,live_odds ,is_visible
,finish_position,dead_heat_flag,distance_from_winner,win_pool,plc_pool,shw_pool
) values(#ID,horse_name,foaling_area,color,sex,breeder_name,sire_name,post_position,program_number ,
weight_carried,scratch_indicator ,trainer_first_name ,owner_name ,jockey_first_name,odds ,owner_silks ,live_odds ,is_visible
,finish_position,dead_heat_flag,distance_from_winner,win_pool,plc_pool,shw_pool);
END LOOP cur_runner_loop;
END BLOCK2;
END LOOP cur_race_loop;
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 118 (0 ms taken)
Could it be a false error as it can not compile as you have no "END" to the overall procedure?. You close out your loops and block, but not the procedure.