Stored procedure MYSQL error - mysql

Having a few issues with running the below procedure over PHPMyAdmin, receiving the error;
"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 6"
The problem seems to be with the IF, the update syntax works on its own, the select within the if statement works on its own.
Any ideas??
CREATE PROCEDURE Get_SessionCookie(
sessionID varchar(50),
cookieID varchar(50)
)
IF (SELECT 1 = 1 FROM `SessionCookie` WHERE SessionID = sessionID AND CookieID = cookieID AND SessionExpiry < NOW())
UPDATE SessionCookie
SET SessionExpiry = NOW() + INTERVAL 60 MINUTE
WHERE SessionID = sessionID AND CookieID = cookieID;
SELECT 'True' FROM SessionCookie;
ELSE
SELECT 'False' FROM SessionCookie;

One major problem is that parameters to the stored procedure have the same names as columns. You should always prefix variable names with something. Your specific problem, I think, is that you want an exists in the if and a delimeter statement. I think this is closer to what you want:
delimiter $$
CREATE PROCEDURE Get_SessionCookie (
var_sessionID varchar(50),
var_cookieID varchar(50)
)
BEGIN
IF exists (SELECT 1
FROM `SessionCookie`
WHERE SessionID = var_sessionID AND
CookieID = var_cookieID AND
SessionExpiry < NOW()
)
UPDATE SessionCookie
SET SessionExpiry = NOW() + INTERVAL 60 MINUTE
WHERE SessionID = var_sessionID AND CookieID = var_cookieID;
SELECT 'True' FROM SessionCookie;
ELSE SELECT 'False' FROM SessionCookie;
END IF
END$$

Related

Unrecognized statement near IF - usage IF with Exists

I want to update the row in table roomstatus where room_id = #id if date_in and date_out are both null. Otherwise, i need to insert new row like where room_id = #id, date_in = #dateIn, date_out = #dateIN
IF ((SELECT date_in FROM roomstatus WHERE room_id = #id)= NULL AND (SELECT date_out FROM roomstatus WHERE room_id = #id)= NULL ) THEN
UPDATE roomstatus SET date_in = #dateIN, date_out = #dateOut WHERE roomid = #id
ELSE
INSERT INTO roomstatus (room_id,date_in,date_out) VALUES (#id,#dateIn,#dateOut)
END IF;
MySQL said:
> #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 'IF ((SELECT date_in FROM roomstatus WHERE room_id = #id)= NULL
> AND (SELECT date_' at line 1
Some things wrong with your procedure
1) Every statement needs a terminator 2) MYSQL cannot differentiate a column name from a parameter name eg WHERE room_id = roomID - (mysql will compare the column to itself) you have to provide that info 3) the end which closes the begin needs to have the closing delimiter. The below is syntactically correct
DROP PROCEDURE IF EXISTS P;
DELIMITER //
CREATE PROCEDURE P(IN INdateIn DATETIME(6) , IN INdateOut DATETIME(6), IN INroomID INT(11))
BEGIN
IF EXISTS (SELECT room_id FROM roomstatus WHERE room_id = INroomID AND date_in = NULL AND date_out = NULL ) THEN
UPDATE roomstatus
SET date_in = INdateIn , date_out = INdateOut
WHERE room_id = INroomID ;
ELSE
INSERT INTO roomstatus (room_id,date_in,date_out) VALUES (INroomID,INdateIn,INdateOut);
END IF;
END //
DELIMITER ;
Functionally I'm not so sure, there is no error checking to ensure that you have set the parameters to achieve what you want to do. For example you are not testing indateout so the code code may enter the update logic with indateout set to null and indatein set to a valid value - next time you call the procedure you may enter the insert logic and possibly end up with a duplicate.

MySQL Stored procedure SELECT var wrong value after INSERT

I have a problem on MySQL stored procedure, already did another logic with IF THEN ELSE, but I still have problems which I cant understand...
The procedure consists on two user inputs: user_id and meet_id. The procedure define a variable called 'ue' which stores result of a bunch of validation (if user exists, if event exists, if event date is still valid, etc.).
After that, it does INSERT and UPDATE some data on multiple tables in IF THEN ELSE selector, and SELECT 1 (or 0) AS result depending of validation.
But my problem is: it always return me 0 as 'result', as if my validation variable was 0 when I do INSERT... And there is where things get weird, if I remove the INSERT [...]; line of the code, it returns me the value of validation correctly (1 or 0).
The code of the procedure is this one:
CREATE DEFINER=`nwouserf`#`localhost`
PROCEDURE `join_event`(IN `user_id` BIGINT(64), IN `event_id` INT)
NOT DETERMINISTIC MODIFIES SQL DATA SQL SECURITY DEFINER
begin
DECLARE ue INT;
SET ue = EXISTS(SELECT 1 FROM users WHERE fb_uid=user_id)
AND EXISTS(SELECT 1 FROM meetup WHERE meet_id=event_id)
AND EXISTS(SELECT 1 FROM meetup WHERE date > NOW() AND meet_id = event_id)
AND EXISTS(SELECT 1 FROM meetup WHERE meet_id = event_id AND participants <= max_participants)
AND NOT EXISTS(SELECT 1 FROM meetup_participation WHERE fb_uid = user_id AND meet_id = event_id);
IF ue = 1 THEN
INSERT INTO meetup_participation (fb_uid, meet_id) VALUES (user_id, event_id);
UPDATE users SET events_participated = events_participated + 1 WHERE fb_uid=user_id;
UPDATE meetup SET participants = participants + 1 WHERE meet_id=event_id;
SELECT 1 AS result;
ELSEIF ue = 0 THEN
SELECT 0 AS result;
ELSE
SELECT null AS result;
END IF;
end
Thanks in advance!
I have been stuck on this for a while now, and can not figure out why.
You should define OUT parameter. Add
", OUT result INT"
immediately after the last IN parameter.

what's wrong with this if/then stored proc?

I'm fuzzy on when I need you use # to reference vars in mySQL. I'm coming from MS SQL where you always use it, but apparently that's not correct in mySQL.
So the below stored procedure is always executing the first IF block, even if the session value is expired - in that it's always executing the update statement. Apparently the only debug tool I could find for mySQL stored procs runs on Windows and Linux. I'm on a Mac. Wamp wamp wamp.
So yeah. Can anyone see what's wrong here? Thanks!
DELIMITER $$
CREATE DEFINER=`xxx`#`localhost` PROCEDURE `validate_session`(uid INT, token VARCHAR(256))
BEGIN
DECLARE sessId INT DEFAULT NULL;
SELECT sessId = id FROM UserSessions
WHERE userId = uid
AND sessionToken = token
AND expires > INTERVAL 2 MINUTE + NOW() ORDER BY expires DESC LIMIT 1;
IF sessId IS NOT NULL THEN
UPDATE UserSessions
SET expires = INTERVAL 2 HOUR + NOW()
WHERE id = sessId;
ELSE
DELETE FROM UserSessions
WHERE userId = uid
AND sessionToken = token;
SET #sessId = 0;
END IF;
SELECT sessId;
END
For the record what it's supposed to do in pseudo code:
if we have a session for this user, with a matching token which has not expired {
update the expiration time to 2 hours from now
return the session id;
}
else {
delete the (now stale) session
return 0;
}
Thanks in advance.
You're not setting the value of sessId... you're making a comparisson in your query.
I think what you need is something like this:
CREATE DEFINER=`xxx`#`localhost` PROCEDURE `validate_session`(uid INT, token VARCHAR(256))
BEGIN
DECLARE sessId INT DEFAULT NULL;
SELECT id
INTO sessId -- Here is the assignment
FROM UserSessions
WHERE userId = uid
AND sessionToken = token
AND expires > INTERVAL 2 MINUTE + NOW()
ORDER BY expires DESC
LIMIT 1;
IF sessId IS NOT NULL THEN
UPDATE UserSessions
SET expires = INTERVAL 2 HOUR + NOW()
WHERE id = sessId;
ELSE
DELETE FROM UserSessions
WHERE userId = uid
AND sessionToken = token;
SET sessId = 0;
END IF;
SELECT sessId;
END
Reference:
MySQL Reference: SELECT ... INTO syntax
MySQL Reference: Local variable scope and resolution

phpMyAdmin can't find syntax for Create EVENT

-mysql 5.6.2
-GLOBAL event_scheduler = ON
Using phpMyAdmin client on MYSQL database. I'm not setting a Delimiter, as I know you can't in this statement. If I remove the last ';', it fails with 'error near END.' In below format, fails with:
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 64
#Begin statement
CREATE EVENT airshipmentsnotinlong
ON SCHEDULE every 1 HOUR
ON COMPLETION PRESERVE
DO
BEGIN
INSERT into WORKORDERS
(
id
,client_id
,method
,carrier_id
,carrier
,username
,password
,blnumber
,containernumber
,bookingnum
,adddate
,moddate
,isdone
)
SELECT
DISTINCT 'null' as ID
,cs.customer_id as client_id
,'justin' as method
,cs.carrier_id
,c.scac
,'' as user
,'' as pass
,cs.blnumber
,cs.container
,'' as book
,now() as adate
,now() as modate
,'0' as done
FROM CUSTOMERSHIPMENTS CS
LEFT JOIN
SHIPMENTS S
ON
cs.container = s.containernumber
and cs.blnumber = s.blnumber
LEFT JOIN
CARRIERS C
ON
cs.carrier_id = c.id
WHERE
cs.hostcompany_id = cs.company_id
and cs.container like '.air%'
and cs.isactive = 1
and cs.hostcompany_id = company_id
and cs.carrier_id in (176,180,222,224,226,227,228,261,271,292,297)
and cs.date > NOW() - INTERVAL 3 MONTH
and cs.blnumber <> ''
#and s.status = ''
and cs.blnumber not in
(
SELECT
blnumber
FROM
workorder_log
WHERE
cdate > now()-interval 75 minute
)
;
END
Your understanding to the contrary notwithstanding, you need to set the delimiter. Do this.
DELIMITER $$
CREATE EVENT airshipmentsnotinlong
ON SCHEDULE every 1 HOUR
ON COMPLETION PRESERVE
DO
BEGIN
...your event's INSERT statement here including the closing semicolon ...
END $$
DELIMITER ;
In PHPMyAdmin, instead of wrapping your definition in DELIMITER $$ / DELIMITER ; you set the delimiter to something besides ; in the box right below the query. You then terminate your definition with that same delimiter, as I have shown in END$$.
The error message you're getting is protesting the missing END, which MySQL doesn't see because it comes after the closing delimiter.

Procedure in MySQL phpmyadmin

I want to make a page view counter in ASP and want check if 10 minutes have passed since last view from some ip. I hve written a procedure in MySQL phpmyadmin that checks that in database.
CREATE PROCEDURE counter(
in ipOfVisitor varchar(30),
in pid int(10))
BEGIN
SELECT #visitor_IP := ip, #date_dif := DATEDIFF( CURDATE( ) , last_counted )
FROM visitors
WHERE ip = ipOfVisitor ;
IF (NOT #visitor_IP = null AND #date_dif > 600) OR #visitor_IP = null THEN
UPDATE patientifo SET numberofclicks = numberofclicks + 1 WHERE id = pid;
END IF;
IF NOT #visitor_IP = null AND #date_dif > 600 THEN
UPDATE visitors SET last_counted = CURDATE( ) where ip = ipOfVisitor;
END IF;
IF #visitor_IP = null THEN
INSERT INTO visitors (ip, last_counted) VALUES (ipOfVisitor, CURDATE ());
END IF;
END
But it gives error
CREATE PROCEDURE counter( IN ipOfVisitor VARCHAR( 30 ) , IN pid INT( 10 ) ) BEGIN SELECT #visitor_IP := ip, #date_dif := DATEDIFF( CURDATE( ) , last_counted )
FROM visitors
WHERE ip = ipOfVisitor;
#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 9
What does it mean?
EDIT
I changed the code like juergen d has said.
DELIMITER |
CREATE PROCEDURE counter(
in ipOfVisitor varchar(30),
in pid int(10))
BEGIN
DECLARE visitor_IP varchar(30);
DECLARE date_dif int(10);
SELECT ip,DATEDIFF( CURDATE( ) , last_counted ) INTO visitor_IP, date_dif
FROM visitors
WHERE ip = ipOfVisitor ;
IF (NOT visitor_IP = null AND date_dif > 600) OR visitor_IP = null THEN
UPDATE patientifo SET numberofclicks = numberofclicks + 1 WHERE id = pid;
END IF;
IF NOT visitor_IP = null AND date_dif > 600 THEN
UPDATE visitors SET last_counted = CURDATE( ) where ip = ipOfVisitor;
END IF;
IF visitor_IP = null THEN
INSERT INTO visitors (ip, last_counted) VALUES (ipOfVisitor, CURDATE ());
END IF;
END
|
And it almost works. Except this error at the last line:
#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 22
You need to change the delimiter. Otherwise the DB thinks your procedure definition ends at the first ; which would be incomplete.
delimiter |
CREATE PROCEDURE counter(
in ipOfVisitor varchar(30),
in pid int(10))
BEGIN
...
END
|