Unrecognized statement near IF - usage IF with Exists - mysql

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.

Related

How to create a parameterized STORED PROCEDURE with CRUD operation in MYSQL Version(6.0.11-alpha-community)

I created a parameterized STORED PROCEDURE with CRUD operation in MYSQL Version(6.0.11-alpha-community)
DELIMITER $$
CREATE PROCEDURE `mae`.`USP_CustomersToken_CURD`(IN CID INT , IN CName VARCHAR(50), IN CToken VARCHAR(250), IN CTokenTime DATETIME , IN OPType INT)
BEGIN
IF (OPType = 1) --Insert
THEN
INSERT INTO tbl_CustomersTokenInfo (ID, CustomerName, Token, TokenTime) VALUES (CID, CName, CToken, CTokenTime)
ELSEIF (OPType = 2) --delete
THEN
DELETE FROM tbl_CustomersTokenInfo WHERE ID = CID
ELSEIF (OPType = 3) --Update
THEN
UPDATE tbl_CustomersTokenInfo SET CustomerName = CName, Token = CToken , TokenTime = CTokenTime WHERE ID = CID
ELSEIF (OPType = 4) --Select
THEN
SELECT * FROM tbl_CustomersTokenInfo WHERE ID =CID
ELSEIF (OPType = 5)--Fetch
THEN
SELECT * FROM tbl_CustomersTokenInfo
END IF
END$$
DELIMITER ;
but when I executing this SP I'm getting this below error :
Query: CREATE PROCEDURE mae.USP_CustomersToken_CURD(IN CID INT , IN CName VARCHAR(50), IN CToken VARCHAR(250), IN CTokenTime DATETI...
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 'THEN
INSERT INTO tbl_CustomersTokenInfo (ID, CustomerName, Token, TokenTime) VAL' at line 4
Execution Time : 0 sec
Transfer Time : 0 sec
Total Time : 0 sec
I'm new to MYSQL commands and syntaxes if I did any mistake give the best approach .
MySQL (unlike most other DBMS) doesn't like comments introduced with -- where no space follows --.
You need to terminate all the statements, including the IF statement (after END IF), with a ;.
Correct that:
DELIMITER $$
CREATE PROCEDURE `mae`.`USP_CustomersToken_CURD`(IN CID INT , IN CName VARCHAR(50), IN CToken VARCHAR(250), IN CTokenTime DATETIME , IN OPType INT)
BEGIN
IF (OPType = 1) -- Insert
THEN
INSERT INTO tbl_CustomersTokenInfo (ID, CustomerName, Token, TokenTime) VALUES (CID, CName, CToken, CTokenTime);
ELSEIF (OPType = 2) -- delete
THEN
DELETE FROM tbl_CustomersTokenInfo WHERE ID = CID;
ELSEIF (OPType = 3) -- Update
THEN
UPDATE tbl_CustomersTokenInfo SET CustomerName = CName, Token = CToken , TokenTime = CTokenTime WHERE ID = CID;
ELSEIF (OPType = 4) -- Select
THEN
SELECT * FROM tbl_CustomersTokenInfo WHERE ID =CID;
ELSEIF (OPType = 5)-- Fetch
THEN
SELECT * FROM tbl_CustomersTokenInfo;
END IF;
END$$
DELIMITER ;

MySQL migrate data from one table to another

I'm attempting to move data from one table to another, as part of a restructure to the database architecture. I'm using PHPMyAdmin and MySQL to do so.
The SQL is meant to, for each emergency_contacts.id, move e_c.id and e_c.activity_id to activities_emergency_contacts, where the pair will form a composite key to link a contact with an activity.
The following SQL returns an error:
CREATE PROCEDURE dowhile()
BEGIN
SET #cid = (SELECT MIN(`id`) FROM `emergency_contacts`);
SET #aid = (SELECT `activity_id` FROM `emergency_contacts` WHERE `id` = #cid);
WHILE #cid IS NOT NULL DO
INSERT INTO activities_emergency_contacts (activity_id, contact_id)
VALUES (#aid, #cid);
SET #cid = (SELECT MIN(id) FROM emergency_contacts WHERE #cid < id);
SET #aid = (SELECT activity_id FROM emergency_contacts WHERE id = #cid);
END WHILE;
END;
CALL dowhile();
SQL query:
CREATE PROCEDURE dowhile() BEGIN SET #cid = (SELECT MIN(id) FROM
emergency_contacts)
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 '' at line 3
I have searched the MySQL specific documentation to try and find any issues with my SET, WHILE, BEGIN/END, INSERT, CREATE - just about every line. I'm unsure how to proceed. Any advice would be greatly appreciated.
EDIT: I missed a closing bracket inside the WHILE on SELECT MIN (id), however I've fixed this and am still getting the exact same issue.
EDIT: The issue was that I was not using DELIMITER. Correct SQL:
DELIMITER $$
CREATE PROCEDURE dowhile()
BEGIN
SET #cid = (SELECT MIN(`id`) FROM `emergency_contacts`);
SET #aid = (SELECT `activity_id` FROM `emergency_contacts` WHERE `id` = #cid);
WHILE #cid IS NOT NULL DO
INSERT INTO activities_emergency_contacts (activity_id, contact_id) VALUES (#aid, #cid);
SET #cid = (SELECT MIN(id) FROM emergency_contacts WHERE #cid < id);
SET #aid = (SELECT activity_id FROM emergency_contacts WHERE id = #cid);
END WHILE;
END$$
DELIMITER ;
CALL dowhile();

MySQL procedure returning wrong value (INSERT SELECT confronting)

I'm completely new to MySQL, and have been bumping with some errors, but always I do find solutions, except for this one I can't understand how to get around it.
The following MySQL Procedure returns me a value if variable "ue" is 1 or 0 (a bunch of exists validation). The validation part (SET ue = EXISTS...) works without the rest of the code, as it should, the problem is not there. But when I do execute the command INSERT INTO SELECT, it does not work, it always return 0 as response, when it should be 1. These two lines are getting in confrontation with each other.
INSERT INTO meetup_participation SELECT user_id, event_id FROM DUAL WHERE ue=1;
SELECT ue AS response;
The procedure should add 'user id' and 'event id' into meetup_participation, and then update the row at 'users' corresponding to the user with that 'user id' to increment the 'events participated'. And it also UPDATE to increment the participation in the event with this 'event id'.
I am using the SET ue to validate things like, if user exists, if event does exists, if date of event is still valid, and if user is not already in this table. So I am passing this value as a boolean to INSERT INTO meetup_participation [...] WHERE ue = 1. After that, I do SELECT ue to inform validation returned true and procedure executed without problems.
Here is the full procedure.
CREATE DEFINER=`user`#`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);
INSERT INTO meetup_participation SELECT user_id, event_id FROM DUAL WHERE ue=1;
UPDATE users SET events_participated = events_participated + 1 WHERE fb_uid=user_id AND ue=1;
UPDATE meetup SET participants = participants + 1 WHERE meet_id=event_id AND ue=1;
SELECT ue AS response;
end
Thanks in advance.
The INSERT statement is executed separately from the SET ue =... statement. I'm not sure what you are trying to accomplish, but the code makes no sense.
If you want to add records to meetup_participation based on the EXISTS tests applied to each record in the users table, you would need to apply the tests to each record in your SELECT statement as part of the INSERT.
There are also numerous syntax/grammar issues in the code as shown.
If you could provide an explanation of what you are trying to accomplish with the procedure, that might allow someone to suggest the right way to code the procedure.
Selecting ue will not tell you if the procedure completed without error. You should research mysql transactions and mysql error handling. http://www.mysqltutorial.org/mysql-error-handling-in-stored-procedures/ is a good starting point.
You might end up with something like this
drop procedure if exists p;
delimiter //
CREATE DEFINER=`root`#`localhost` PROCEDURE `p`(
IN `inue` int,
IN `user_id` BIGINT(64),
IN `event_id` INT
)
LANGUAGE SQL
NOT DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY DEFINER
COMMENT ''
begin
DECLARE ue INT;
declare exit handler for sqlexception
begin
rollback;
insert into errors (msg) select concat('error ' ,inue,',',user_id,',',event_id);
end;
set autocommit = 0;
#set ue = inue;
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 dt > NOW() AND meet_id = event_id)
AND EXISTS(SELECT 1 FROM meetup WHERE meet_id = event_id AND ifnull(participants,0) <= max_participants)
AND NOT EXISTS(SELECT 1 FROM meetup_participation WHERE fb_uid = user_id AND meet_id = event_id)
;
select ue;
if ue = 1 then
start transaction;
INSERT INTO meetup_participation SELECT user_id, event_id,user_id, event_id;
UPDATE users SET events_participated = ifnull(events_participated,0) + 1 WHERE fb_uid=user_id = user_id;
UPDATE meetup SET participants = ifnull(participants,0) + 1 WHERE meet_id = event_id ;
commit;
end if;
SELECT ue AS response;
end //
The error table looks like this
CREATE TABLE `errors` (
`msg` varchar(2000) DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
Note I am not suggesting this is a solution appropriate to your site , you need to do the research and figure out what is best for you.

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
|

Stored procedure MYSQL error

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$$