Procedure in MySQL phpmyadmin - mysql

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
|

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 ;

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.

Error in creating procedure in MySQL

What may be the possibilities of getting an error in the following query?
DELIMITER $$
CREATE PROCEDURE `tbl_assessment_notes`(
`var_reason` VARCHAR,
'var_attr2' VARCHAR,
'var_note' VARCHAR
)
BEGIN
IF EXISTS
(
SELECT
*
FROM
tbl_assessment_notes
WHERE
reason = var_reason AND attr2 = var_attr2
) THEN
UPDATE
tbl_assessment_notes
SET
note = CONCAT(note, var_note),
TIMESTAMP = 'CURRENT_TIMESTAMP'
WHERE
attr1 = var_attr1 AND reason = var_reason ELSE
INSERT
INTO
tbl_assessment_notes(
pk_assess_note_id,
attr2,
attr3,
reason,
note,
TIMESTAMP
)
VALUES(
NULL,
var_attr2,
NULL,
'confirmation',
var_note,
'CURRENT_TIMESTAMP'
) ;
END IF ;
END $$
DELIMITER ;
I'm getting the following 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 '
'var_reason' VARCHAR,
'var_attr2' VARCHAR,
`var_note` VARCHAR,
'var' at line 2
Basically what I'm trying to do is to update a row if it exists or else creates a new row and insert values into it.
Please use updated query
DELIMITER $$
CREATE PROCEDURE `tbl_assessment_notes`
(var_reason VARCHAR(255),
var_attr2 VARCHAR(255),
var_note VARCHAR(255))
BEGIN
IF EXISTS
(
SELECT
*
FROM
tbl_assessment_notes
WHERE
reason = var_reason AND attr2 = var_attr2 ) THEN UPDATE tbl_assessment_notes SET note = CONCAT(note, var_note), TIMESTAMP
= 'CURRENT_TIMESTAMP' WHERE attr1 = var_attr1 AND reason = var_reason ELSE INSERT INTO tbl_assessment_notes(
pk_assess_note_id,
attr2,
attr3,
reason,
note,
TIMESTAMP) VALUES(NULL,var_attr2,NULL,'confirmation', var_note, 'CURRENT_TIMESTAMP' ) ;
END IF ;
END $$
DELIMITER ;

All Tables cant' perform INSERT OR UPDATE

I used a stored procedure that uses a cursor to loop through and process an attendance data table on Mariadb 10.1 database after calling the procedure the first time all the tables on the database lost the ability to perform INSERT INTO or UPDATE statements unless the targeted table is truncated first, can any one tell me what went wrong and how to fix it
the procedure that caused the problem:
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `settle_attendance`()
MODIFIES SQL DATA
BEGIN
DECLARE trans_done BOOLEAN DEFAULT FALSE;
DECLARE punchid BIGINT(20);
DECLARE timein DATETIME;
DECLARE utctimein DATETIME;
DECLARE timeout DATETIME;
DECLARE utctimeout DATETIME;
DECLARE inday DATE;
DECLARE outday DATE;
DECLARE todaysdate DATE;
DECLARE attendcur CURSOR FOR
SELECT id, punch_in_utc_time, punch_in_user_time,
punch_out_utc_time, punch_out_user_time
FROM ohrm_attendance_record
ORDER BY id ASC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET trans_done = TRUE;
OPEN attendcur;
edit_loop: LOOP
SET todaysdate = CURRENT_DATE();
FETCH attendcur INTO punchid, utctimein, timein, utctimeout, timeout;
IF trans_done THEN
CLOSE attendcur;
LEAVE edit_loop;
END IF;
SET inday = DATE(timein);
SET outday = DATE(timeout);
SET todaysdate = CURRENT_DATE();
IF (inday < todaysdate) OR (outday < todaysdate) THEN
CASE
WHEN (timein IS NULL OR timein = '')
OR (utctimein IS NULL OR utctimein = '') THEN
UPDATE ohrm_attendance_record
SET punch_in_utc_time = utctimeout,
punch_in_user_time = timeout,
state = 'PUNCHED OUT'
WHERE punchid = id;
ELSE BEGIN END;
END CASE;
CASE
WHEN (timeout IS NULL OR timeout = '')
OR (utctimeout IS NULL OR utctimeout = '') THEN
UPDATE ohrm_attendance_record
SET punch_out_utc_time = utctimein,
punch_out_user_time = timein,
state = 'PUNCHED OUT'
WHERE punchid = id;
ELSE BEGIN END;
END CASE;
END IF;
END LOOP edit_loop;
END $$
DELIMITER ;
I choose to avoid the question you asked. Instead, let's try to do the query 10 times as fast by getting rid of the pesky CURSOR. The entire Stored Procedure can be done in 2 UPDATEs, no loop:
UPDATE ohrm_attendance_record
SET punch_in_utc_time = utctimeout,
punch_in_user_time = timeout,
state = 'PUNCHED OUT'
WHERE ( timein < CURDATE() OR timeout < CURDATE() )
AND ( ( timein IS NULL OR timein = '' )
OR ( utctimein IS NULL OR utctimein = '' )
);
UPDATE ohrm_attendance_record
SET punch_out_utc_time = utctimein,
punch_out_user_time = timein,
state = 'PUNCHED OUT'
WHERE ( timein < CURDATE() OR timeout < CURDATE() )
AND ( ( timeout IS NULL OR timeout = '' )
OR ( utctimeout IS NULL OR utctimeout = '' )
);
I am, however, suspicious of your tests against timein and timeout.
The queries would be easier to read if you settled on either NULL or '' for missing times.
If you store only UTC values in a TIMESTAMP, you can let the user's timezone take care of coverting to local time -- this would eliminate quite a few columns and simplify the UPDATEs.
I'll make a stab at the question... Do SHOW CREATE PROCEDURE settle_attendance;, you may find that the CHARACTER SET or COLLATION is inconsistent with what you think it should be.

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