Sql syntax error in procedure - mysql

I am writing one procedure in order to get data from database .
Here is my procedure .
CREATE DEFINER=`root`#`localhost` PROCEDURE `getCdrListnew`(from_date DATETIME, to_date DATETIME,
p_category VARCHAR(255), p_callType VARCHAR(255), p_businessId VARCHAR(255), p_dnc VARCHAR(255),
p_cli VARCHAR(255), p_dni VARCHAR(255), p_callNumber VARCHAR(255), p_dialType VARCHAR(255), p_contractType VARCHAR(255) )
BEGIN
DECLARE a INT ;
DECLARE setFilter INT DEFAULT FALSE;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET a = 0;
BEGIN
END;
SET #sqlCalls = 'SELECT agentcdr.isdnCauseCode,COUNT(*) as count FROM cdr';
-- SET #sqlCalls= CONCAT(#sqlCalls,' LEFT JOIN agentcdr ON cdr.idCDR=agentcdr.cdr_idCDR ');
IF( (from_date IS NOT NULL AND from_date != '')&& (to_date IS NOT NULL AND to_date != '') ) THEN
SET #sqlCalls= CONCAT(#sqlCalls,' WHERE cdr.createdDt >=\'',from_date,'\' AND cdr.createdDT<=', '\'',to_date,'\'');
SET setFilter = TRUE;
END IF;
SET #sqlCalls= CONCAT(#sqlCalls,' LEFT JOIN agentcdr ON cdr.idCDR=agentcdr.cdr_idCDR GROUP BY agentcdr.isdnCauseCode ');
PREPARE prepsqlstr1 FROM #sqlCalls;
EXECUTE prepsqlstr1;
END
When I am executing the above code I am getting an error as below .
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 'LEFT JOIN agentcdr ON cdr.idCDR=agentcdr.cdr_idCDR GROUP BY agentcdr.isdnCauseCo' at line 1
I know this is the syntax problem but not able to figure out what I am doing wrong here .
Please help me out .
ALso do let me know if there any way to print the query which is executing in procedure for debugging purpose .

Looks like you have a wrong order in the generated statement:
You get a select ... where ... left join .... This is wrong syntax.

Related

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 ;

MySQL - CREATE DEFINER syntax error

I am trying to update a stored function in our MySQL database. The update is to be released to multiple devices so I am doing it through an update.sql file.
Here is the function
DROP FUNCTION `STAFF_MPT`;
CREATE DEFINER=`jelena`#`%` FUNCTION `STAFF_MPT`(`par_stocktake_staff_id` INT) RETURNS DECIMAL(20,0) NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER BEGIN
DECLARE proc_total INT;
DECLARE proc_time INT;
SET proc_total = (SELECT SUM(quantity) FROM stocktake_scans WHERE stocktake_staff_id = par_stocktake_staff_id);
SET proc_time = (SELECT TIMESTAMPDIFF( SECOND , MIN( scan_date ) , MAX( scan_date ) ) AS area_time
FROM stocktake_scans
WHERE stocktake_staff_id = par_stocktake_staff_id
);
RETURN (proc_total/proc_time)*3600;
END
It was just reported to me by the test team that the report that uses this function did not generate properly. I tried to run the code in PMA SQL query window and got the following:
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
Can someone tell me what am I missing? According to this, line 3 is empty, so how could it possibly have a syntax error?
As of MySQL docs:
If you use the mysql client program to define a stored program containing semicolon characters, a problem arises. By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the delimiter temporarily to cause mysql to pass the entire stored program definition to the server.
To redefine the mysql delimiter, use the delimiter command.
#juergen_d hinted in the comment: you have to define your procedure with a delimiter:
DROP FUNCTION `STAFF_MPT`;
delimiter ||
CREATE DEFINER=`jelena`#`%` FUNCTION `STAFF_MPT`(`par_stocktake_staff_id` INT) RETURNS DECIMAL(20,0) NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER BEGIN
DECLARE proc_total INT;
DECLARE proc_time INT;
SET proc_total = (SELECT SUM(quantity) FROM stocktake_scans WHERE stocktake_staff_id = par_stocktake_staff_id);
SET proc_time = (SELECT TIMESTAMPDIFF( SECOND , MIN( scan_date ) , MAX( scan_date ) ) AS area_time
FROM stocktake_scans
WHERE stocktake_staff_id = par_stocktake_staff_id
);
RETURN (proc_total/proc_time)*3600;
END
||
delimiter ;

How Can I Create a MySQL Function to Check JSON Validity?

I'm fairly new to MySQL but I'd like to create a function to validate a JSON objects that are stored in my database tables.
I looked up information on creating a function, but must be missing something as I can't seem to get it to work. It doesn't seem like it would be overly complicated but perhaps I'm not using the appropriate syntax.
Here is my code:
DELIMITER //
CREATE FUNCTION CHECKJSON( DB_NAME varchar(255), TABLE_NAME varchar(255), JSON_COLUMN varchar(255))
RETURNS varchar(300)
BEGIN
DECLARE notNullCount int;
DECLARE validJSONCount int;
DECLARE result varchar(300);
SET notNullCount = (SELECT count(*) FROM DB_NAME.TABLE_NAME WHERE JSON_COLUMN IS NOT NULL);
set validJSONCount = (SELECT count(*) FROM DB_NAME.TABLE_NAME WHERE JSON_VALID(JSON_COLUMN) > 0);
CASE
WHEN (validJSONCount = notNullCount) THEN
SET result = CONCAT('VALID JSON COUNT: ', validJSONCount)
ELSE
SET result = CONCAT('INVALID JSON COUNT: ', (notNullCount - validJSONCount))
END;
RETURN result;
END //
DELIMITER ;
When I try to run this code, I get the following error message:
"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 'ELSE SET result = CONCAT('INVALID JSON COUNT: ', (notNullCount - validJSONC' at line 14"
Any thoughts on how I might improve this code? Thanks!
Since MySQL 5.7 you have a pretty and simple function for this:
JSON_VALID(value)
Returns 0 or 1 to indicate whether a value is valid JSON. Returns NULL if the argument is NULL.
https://dev.mysql.com/doc/refman/5.7/en/json-attribute-functions.html#function_json-valid
You're missing a couple of ; and to end the case it should be END CASE.
DELIMITER //
CREATE FUNCTION CHECKJSON( DB_NAME varchar(255), TABLE_NAME varchar(255), JSON_COLUMN varchar(255))
RETURNS varchar(300)
BEGIN
DECLARE notNullCount int;
DECLARE validJSONCount int;
DECLARE result varchar(300);
SET notNullCount = (SELECT count(*) FROM DB_NAME.TABLE_NAME WHERE JSON_COLUMN IS NOT NULL);
set validJSONCount = (SELECT count(*) FROM DB_NAME.TABLE_NAME WHERE JSON_VALID(JSON_COLUMN) > 0);
CASE
WHEN (validJSONCount = notNullCount) THEN
SET result = CONCAT('VALID JSON COUNT: ', validJSONCount) ;
ELSE
SET result = CONCAT('INVALID JSON COUNT: ', (notNullCount - validJSONCount)) ;
END CASE;
RETURN result;
END //
DELIMITER ;

Why my sql query not runing as I have set the right DELIMITER

DELIMITER $$
ALTER PROCEDURE GetUContent(IN CurPage INT,IN PageRows INT)
BEGIN
DECLARE #rownum INT DEFAULT 0;
SELECT #rownum:=#rownum+1 as T_ROWID,
tcl.T_ID AS T_CID ,
tcl.T_CONTENTS ,
tcl.T_TYPE ,
tcl.T_STATUS ,
tcl.T_GOAL ,
tcl.T_IMGURL AS T_CIMGURL ,
tcl.T_CREATETIME ,
tul.T_ID AS T_UID ,
tul.T_NAME ,
tul.T_IMGURL AS T_UIMGURL ,
IFNULL(trl.T_RCOUNT, 0) AS T_RCOUNT
FROM T_CONTENT tcl LEFT JOIN
( SELECT T_CID , COUNT(T_ID) AS T_RCOUNT
FROM T_REPLAY WHERE T_STATUS = 1 GROUP BY T_CID
) trl ON tcl.T_ID = trl.T_CID
INNER JOIN T_USERINFO tul ON tcl.T_UID = tul.T_ID
WHERE tcl.T_STATUS = 1
ORDER BY tcl.T_CREATETIME LIMIT PageRows*CurPage,PageRows;
END $$
DELIMITER ;
Error Info:
ERROR 1064 (42000) at line 2 in file: '/root/git/Thinking/src/main/resources/dataScript.sql': You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CurPage INT,IN PageRows INT)
BEGIN
DECLARE #rownum INT DEFAULT 0;
SELECT ' at line 1
Must Infomation:
I use the default mysql client
Runing Command: . /root/git/Thinking/src/main/resources/dataScript.sql
The content of dataScipt.sql is the upper coding.
I think you need to use
DECLARE rownum INT DEFAULT 0;
SELECT rownum=rownum+1 as T_ROWID,
...
because #... variables are session variables that cannot be used with DECLARE.
EDIT
And ALTER PROCEDURE does not support changing the method body in MariaDB:
However, you cannot change the parameters or body of a stored
procedure using this statement; to make such changes, you must drop
and re-create the procedure using DROP PROCEDURE and CREATE PROCEDURE.

MySQL Stored Procedure Declare Issue

This problem has cost me almost an hour now and I know it is something simple.
I am 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 'IN VARCHAR(256), hl7PatientId IN VARCHAR(256))
BEGIN
DECLARE mainQueue INT' at line 1
Here is my query which looks right to me:
DROP PROCEDURE IF EXISTS insert_data;
CREATE PROCEDURE `insert_data`(hl7PatientName IN VARCHAR(256), hl7PatientId IN VARCHAR(256))
BEGIN
DECLARE mainQueue INT DEFAULT 1;
SELECT `queueid` INTO mainQueue FROM `queues` WHERE `description` LIKE 'Main' AND `enabled` = 1 LIMIT 1;
INSERT INTO `queue_data`
(`queueid`, `patientname`, `patientid`, `location`, `creationtime`, `priority`)
VALUES
(mainQueue, hl7PatientName, hl7PatientId, 'QUEUE_NUMBER', TIMESTAMP(), '');
END;
I am using MySQL 5.0.77 for this.
Can anybody see anything in this that is wrong?
i've tidied up your example a little - note the use of delimiter and in params !
drop procedure if exists insert_queue_data;
delimiter #
create procedure insert_queue_data
(
in p_patientname varchar(255), -- size ? i always prefix my params p_ and keep the same name as the db field
in p_patientid varchar(255) -- size ? are you sure this isnt an integer ?
)
begin
-- i always prefix my variables v_ and keep same name as the db field
declare v_queueid int unsigned default 1;
select queueid into v_queueid from queues where
description like 'Main' and enabled = 1 limit 1;
insert into queue_data(queueid, patientname, patientid, location, creationtime, priority) values
(v_queueid, p_patientname, p_patientid, 'QUEUE_NUMBER', now(), '');
end#
delimiter ;
Reverse the order of IN and parameter name.
...(IN hl7PatientName VARCHAR(256), IN hl7PatientId VARCHAR(256))...