Hi I've a student table where I have columns like username, usertype, password etc.
I have wrote a trigger for the this table which creates a username for the for the usertype 'Student', Here is the trigger codes
> DROP TRIGGER `sasis`.`USERNAMEAutoGen`;
DELIMITER ||
CREATE TRIGGER `sasis`.`USERNAMEAutoGen`
BEFORE INSERT ON `sasis`.`userinfo`
FOR EACH ROW BEGIN
if (usertype== 'Student')
declare i varchar(2);
declare usrnm varchar(20);
declare fullusrnm varchar(255);
declare curyr varchar(10);
declare curm varchar(10);
declare rcount varchar(50);
set i='I';
select date_format(now(),'%y') into curyr;
select date_format(now(),'%b') into curm;
set usrnm=concat(i,curyr,upper(curm));
select count(*) into rcount from userinfo where username like concat(usrnm,'%');
if(rcount<9) then
set rcount=concat('0000',(rcount+1));
elseif (rcount<99) then
set rcount=concat('000',(rcount+1));
elseif (rcount<999) then
set rcount=concat('00',(rcount+1));
end if;
set fullusrnm=concat(i,curyr,upper(curm),rcount);
if (new.username is null or trim(new.username)='') then
set NEW.username=fullusrnm;
end if; end if; END||
DELIMITER ;
It was working before, but now its showing some error which states that there is a syntax error near '=='Student') declare i varchar(2). etc. And I have no clue how to solve it
please help with your valuable answers. Thanks in advance.
I have tried with "if (usertype= 'Student') THEN" as well but then it shows error message like syntax error near declare i varchar(2);
As I browsed on the manual, I can't see any == supported,
MySQL OPERATORS
So in your TRIGGER, should only be IF (usertype = 'Student') THEN
FULL TRIGGER CODE
CREATE TRIGGER `sasis`.`USERNAMEAutoGen`
BEFORE INSERT ON `sasis`.`userinfo`
FOR EACH ROW
BEGIN
declare i varchar(2);
declare usrnm varchar(20);
declare fullusrnm varchar(255);
declare curyr varchar(10);
declare curm varchar(10);
declare rcount varchar(50);
IF (usertype== 'Student') THEN
set i='I';
select date_format(now(),'%y') into curyr;
select date_format(now(),'%b') into curm;
set usrnm=concat(i,curyr,upper(curm));
select count(*) into rcount from userinfo where username like concat(usrnm,'%');
if(rcount<9) then
set rcount=concat('0000',(rcount+1));
elseif (rcount<99) then
set rcount=concat('000',(rcount+1));
elseif (rcount<999) then
set rcount=concat('00',(rcount+1));
end if;
set fullusrnm=concat(i,curyr,upper(curm),rcount);
if (new.username is null or trim(new.username)='') then
set NEW.username=fullusrnm;
end if;
end if;
END||
DELIMITER ;
are you sure mysql allows == as equality operator?
Related
I want to copy all recoreds from temp1 table to anoter two tables I am using cursor for this .
DELIMITER //
CREATE PROCEDURE cpyQ()
BEGIN
DECLARE g_id INT DEFAULT 0;
DECLARE v_fn varchar(100);
DECLARE v_ln varchar(100);
DECLARE v_email varchar(100);
declare tcursor for select distinct mailid,fname,lname from temp1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET flag = 1;
OPEN tcursor;
REPEAT
FETCH cursor into v_fn,v_ln, v_email;
insert into atom(type) values('Person');
SET g_id = LAST_INSERT_ID();
insert into user(id,fname,lname,mailid) values(g_id,v_fname,v_lname,v_email);
END REPEAT;
CLOSE tcursor;
END//
DELIMITER
this code is showing error
MySQL said: Documentation
#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 'for select distinct mailid,fname,lname from temp1;
DECLARE CONTINUE HANDLE' at line 8
How to resolve this
You have multiple errors in your syntax and don't exit the loop. Try this?
CREATE PROCEDURE cpyQ()
BEGIN
DECLARE g_id INT DEFAULT 0;
DECLARE v_fn varchar(100);
DECLARE v_ln varchar(100);
DECLARE v_email varchar(100);
DECLARE done INT DEFAULT FALSE;
declare tcursor cursor for select distinct mailid,fname,lname from temp1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN tcursor;
read_loop: LOOP
FETCH tcursor into v_fn,v_ln, v_email;
if done then
LEAVE read_loop;
END IF;
insert into atom(type) values('Person');
SET g_id = LAST_INSERT_ID();
insert into user(id,fname,lname,mailid) values(g_id,v_fn,v_ln,v_email);
END LOOP;
CLOSE tcursor;
END
I tried this query and find this is working
insert into atom(id,type) select id,'Person' from user1;
INSERT INTO user( id, fname, lname, mailid ) SELECT id, fname, lname, mailid FROM user1;
I have below set statements for MSSQL, which works perfect :
Declare #uid INT;
Declare #ct int;
Declare #code int;
Declare #usertype int;
Declare #flag char;
Declare #max_itemid int;
Declare #ulname varchar(10);
Declare #ufname varchar(10);
set #code= 123;
set #ulname='Will';
set #ufname='Smith';
set #max_itemid=(select max(itemid) from registration;
set #uid = (select uid from users where ulname=#ulname and ufname=#ufname)
set #ct=(select count(*) from usercodes where itemId=#uid)
set #usertype=(select usertype from users where uid=#uid)
If(#usertype=1)
begin
If (#uid>0)
Begin
select * from users where uid=#uid;
select * from usercodes where itemId=#uid;
if(#ct=0)
begin
if (#max_itemid=2 or #max_itemid=0)
set #flag='D';
else
set #flag='O';
insert into usercodes (itemId,CODE,Flag) values(#uid,#code,#flag);
select * from usercodes where itemId=#uid;
else
begin
PRINT 'UserCode is already added and below is result:';
select * from usercodes where itemId=#uid;
end
end
Else
PRINT 'No User Found';
end
else
begin
print 'User not added as usertype is ';PRINT #usertype;
end
Now i am a newbee to Mysql and want to rewrite the above statements as per the Mysql conventions. I figured out the syntax, and changes the declarations as :
SET #CODE='S10_12345' ;
SET #NAME='Will Smith';
and so on.
But the executions stops once it enters the IF statement. Can someone help figuring out where I am wrong ?
P.S. I am not using any procedures/functions - i can't store these bunch of statements as I have to customize the select statements as the DB can change each time.
I am trying to create and set a variable:
DECLARE myId INT;
SET myId = 5;
However, I am getting invalid syntax complaint in MySQL Workbench:
SQL syntax error near 'DECLARE myId INT;'
I have tried the following variants:
DECLARE myId INT(4);
SET myId = 5;
DECLARE #myId INT;
SET #myId = 5;
DECLARE #myId INT(4);
SET #myId = 5;
What is wrong?
Try
SET #myId := 100;
Then if you do
select #myId;
You will get
100
As in the comment says Declare is only valid into stored programs like procedures, functions.
here you have an example of a store procedure and its call.
DELIMITER $$
CREATE PROCEDURE sp1 (x VARCHAR(5))
BEGIN
DECLARE xname VARCHAR(5) DEFAULT 'bob';
DECLARE myId INT;
SET myId = 5;
SELECT CONCAT(xname,' -- ',myId);
END;
$$
DELIMITER ;
call sp1('MY NAME');
I experienced the same problem. The variables must be declared at the beginning of the script.
DELIMITER &&
DROP PROCEDURE IF EXISTS PS_HANDLERS;
CREATE PROCEDURE PS_HANDLERS(IN ID_USER INT, OUT isError INT)
BEGIN
DECLARE USER_EMAIL VARCHAR(50);
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
SET IsError = 1;
END;
SET USER_EMAIL = CONCAT(RAND(),'#',RAND(),'.com');
SET isError = 0;
INSERT INTO tbl_user VALUES(ID_USER, 'ipsum','lorem','ipsum#lorem.com','password','ROLE_USER');
SELECT
u.*
FROM
tbl_user u;
END &&
DELIMITER ;
Stored procedure:
CREATE PROCEDURE lead_to_loan(xReffID_list text)
I want to use this xReffID_list variable in a select statement as
SELECT * FROM XXXX where xreffID IN (xReffID_list);
but the xreffID is a int Variable
How Can I use xReffID_list text which is a string of comma separated numbers in the INcondition for int variables ?
Stored procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS lead_to_loan$$
CREATE PROCEDURE lead_to_loan(XRefID_list text)
BEGIN
DECLARE loanCount int(11) default 0;
DECLARE matchCount int(11) default 0;
DECLARE loan_XRefID int(11);
DECLARE loan_LEADS360ID int(11);
DECLARE loan_email varchar(100);
DECLARE loan_phone varchar(30);
DECLARE loan_cellphone varchar(20);
DECLARE loan_workphone varchar(20);
DECLARE loan_closeDate datetime;
DECLARE loan_FundedDate datetime;
DECLARE lead_id int(11);
DECLARE lead_RefId varchar(100);
DECLARE lead_Email varchar(100);
DECLARE lead_DayPhone varchar(50);
DECLARE lead_EveningPhone varchar(20);
DECLARE lead_Cellphone varchar(20);
DECLARE lead_DateAdded varchar(30);
DECLARE done boolean default false;
DECLARE startTime datetime;
DECLARE cursor_loanDetail CURSOR FOR
SELECT XRefID,LEADS360ID,email,phone,cellphone,workphone,closeDate,FundedDate
FROM fsbcorponline.view_loandetail where find_in_set(XRefID, XRefID_list) > 0;
DECLARE cursor_loanMatchLeads CURSOR FOR
SELECT id,RefId,Email,DayPhone,EveningPhone,Cellphone,DateAdded
FROM fsbcorponline.leads360leads
WHERE RefId !="" AND RefId IS NOT NULL AND RefId =loan_LEADS360ID AND loan_LEADS360ID>0 OR
Email !="" AND Email IS NOT NULL AND Email =loan_email OR
DayPhone !="" AND DayPhone IS NOT NULL AND DayPhone = loan_workphone OR
EveningPhone !="" AND EveningPhone IS NOT NULL AND EveningPhone= loan_phone OR
Cellphone !="" AND Cellphone IS NOT NULL AND Cellphone =loan_cellphone;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
set startTime = now();
OPEN cursor_loanDetail;
cursor_loanDetail_loop: loop
fetch cursor_loanDetail into loan_XRefID,loan_LEADS360ID,loan_email,loan_phone,loan_cellphone,loan_workphone,loan_closeDate,loan_FundedDate;
if done then
set done = false;
leave cursor_loanDetail_loop;
END if;
SET loanCount = loanCount+1;
OPEN cursor_loanMatchLeads;
cursor_loanMatchLeads_loop: loop
fetch cursor_loanMatchLeads into lead_id,lead_RefId,lead_Email,lead_DayPhone,lead_EveningPhone,lead_Cellphone,lead_DateAdded;
if done then
set done = false;
leave cursor_loanMatchLeads_loop;
END if;
SET matchCount = matchCount+1;
INSERT INTO `fsbcorponline`.`leads_to_loan`(`lead_id`,`lead_RefId`,`lead_Email`,`lead_DayPhone`,`lead_EveningPhone`,`lead_Cellphone`,`lead_DateAdded`,`loan_XRefID`,`loan_LEADS360ID`,`loan_email`,`loan_phone`,`loan_cellphone`,`loan_workphone`,`loan_closeDate`,`loan_FundedDate`)
VALUES(lead_id,lead_RefId,lead_Email,lead_DayPhone,lead_EveningPhone,lead_Cellphone,lead_DateAdded,loan_XRefID,loan_LEADS360ID,loan_email,loan_phone,loan_cellphone,loan_workphone,loan_closeDate,loan_FundedDate)
ON duplicate key update loan_updateCount = loan_updateCount +1 ;
leave cursor_loanMatchLeads_loop;
END loop cursor_loanMatchLeads_loop;
CLOSE cursor_loanMatchLeads;
END loop cursor_loanDetail_loop;
close cursor_loanDetail;
INSERT INTO `fsbcorponline`.`log`(`processName`,`pageName`,`path`,`status`,`note`,`processStartTime`,`processEndTime`)
VALUES('Store Procedure','Lead_to_Loan','Database','1',CONCAT('Loan Matches ',matchCount,' of total ',loanCount),startTime,now());
END$$
DELIMITER ;
You can use find_in_set to do this:
SELECT * FROM XXXX WHERE find_in_set(xreffID, xreffID_list) > 0
Hey you can use cast() function available with Mysql
http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html#function_cast
Hope this will help you.
delimiter $$
CREATE TRIGGER REDUCE_NOTE_COUNT
AFTER DELETE ON iv_notes
FOR EACH ROW BEGIN
DECLARE supplierid int(11);
DECLARE customerid int(11);
SELECT supplierid ,customerid FROM iv_documents WHERE id=OLD.note_documentid;
SET supplierid=supplierid;
SET customerid=customerid;
IF supplierid=OLD.note_companyid THEN
update iv_documents
set supplier_notes=supplier_notes-1
where id=OLD.note_documentid and supplier_notes>0;
END IF;
IF customerid=OLD.note_companyid THEN
update iv_documents set customer_notes=customer_notes-1
where id=OLD.note_documentid
and customer_notes>0 ;
END IF;
END$$
delimiter ;
You cannot execute SELECT statements from trigger. If you want to set variables, then use SELECT INTO statement, e.g. -
DECLARE supplierid_ INT(11);
DECLARE customerid_ INT(11);
SELECT
supplierid, customerid
INTO
supplierid_, customerid_
FROM
iv_documents
WHERE
id = OLD.note_documentid;
IF supplierid_ = OLD.note_companyid THEN
...
Also, rename variables, they have to differ from from field names.