Stored procedure error when being called - mysql

When I call my procedure, it return an 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 'NULL' at line 1
How to fix it, do I have an error in my procedure code?
Here is my stored procedure :
DELIMITER $$
DROP PROCEDURE IF EXISTS `gamedb`.`ALIAS#SEARCH`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `ALIAS#SEARCH`(
in section_id varchar(255),
in category_id varchar(255),
in content_id varchar(255)
)
BEGIN
declare q varchar(4000);
set #q = 'SELECT * FROM tbl_alias WHERE ALIAS_ACTIVE_STATUS=1';
IF section_id IS NOT NULL THEN
set #q = concat(q,' AND ALIAS_SECTION_ID = ',section_id);
END IF;
IF category_id IS NOT NULL THEN
set #q = concat(q,' AND ALIAS_CATEGORY_ID = ',category_id);
END IF;
IF content_id IS NOT NULL THEN
set #q = concat(q,' AND ALIAS_CONTENT_ID = ',content_id);
END IF;
set #q= concat(q,' ORDER BY ALIAS_ID DESC');
prepare stmt from #q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;

There several problems
Since you can PREPARE only from user variable, you don't need a local variable q
You're missing # for #q variable when using CONCAT()
set #q = concat(q,' AND ALIAS_SECTION_ID = ',section_id);
^
Since your IN parameters defined as VARCHAR you better quote their values when you build the query
That being said your SP might look like this
DELIMITER $$
CREATE PROCEDURE `ALIAS#SEARCH`(
in section_id varchar(255),
in category_id varchar(255),
in content_id varchar(255)
)
BEGIN
SET #q = 'SELECT * FROM tbl_alias WHERE ALIAS_ACTIVE_STATUS = 1';
IF section_id IS NOT NULL THEN
SET #q = CONCAT(#q, ' AND ALIAS_SECTION_ID = ''', section_id, '''');
END IF;
IF category_id IS NOT NULL THEN
SET #q = CONCAT(#q, ' AND ALIAS_CATEGORY_ID = ''', category_id, '''');
END IF;
IF content_id IS NOT NULL THEN
SET #q = CONCAT(#q, ' AND ALIAS_CONTENT_ID = ''', content_id, '''');
END IF;
SET #q = CONCAT(#q, ' ORDER BY ALIAS_ID DESC');
PREPARE stmt FROM #q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;

Related

Table exists on database MySQL using Stored Procedure

Is there a way to check if a table exists on database MySQL using Stored Procedure?
This is the SP, I expected when the table exists the variable value titem_id return 1 and when table not exists the variable value titem_id return 0.
Instead in all conditions (the table exists or not) the value is always zero...
Help me to do it.
I don't need number of records but check if exist table in database.
If table exists the return of value titem_id it's 1 else it's 0.
CREATE DEFINER=`root`#`%` PROCEDURE `SP`(tmonth int(2), tddlarea CHAR(100), OUT titem_id INT(11))
BEGIN
DECLARE 2tmonth int(2);
DECLARE 2tddlarea char(100);
DECLARE 2tyear int(4);
DECLARE 2titem_id int(11);
SET 2tmonth = tmonth;
SET 2tddlarea = tddlarea;
SET 2tyear = YEAR(CURDATE());
SET 2titem_id = 0;
SET #t = CONCAT('SELECT EXISTS(SELECT * FROM INFORMATION_SCHEMA.tables AS titem_id
WHERE table_schema = ''db''
AND table_name = ''t_contents_', 2tddlarea, '_', 2tmonth, '_', 2tyear, ''');');
PREPARE stmt FROM #t;
EXECUTE stmt;
DEALLOCATE PREPARE `stmt`;
SELECT #t;
IF #t = 1 THEN
SET titem_id := 1;
SET #s = -- EXECUTE SQL QUERY
PREPARE stmt FROM #s;
EXECUTE stmt;
DEALLOCATE PREPARE `stmt`;
ELSE
SET titem_id := 0;
END IF;
END
UPDATE
CALL sys.table_exists('db', CONCAT('t_contents_', 2tddlarea, '_', 2tmonth, '_', 2tyear, ''), #exists);
SELECT #exists;
IF #exists > '' THEN
SET titem_id = 1;
SET #s = -- -- EXECUTE SQL QUERY
PREPARE stmt FROM #s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
ELSE
SET titem_id = 0;
END IF;

Do something if a table exists

I am trying to find out if there a table called OOK and if so, do something to it. This is what I have so far, which does not work with a helpful ERROR 1064 […] syntax error message:
IF show tables like 'OOK' THEN
DELETE FROM OOK WHERE Id = 'Development';
INSERT INTO OOK VALUES ( 'Development', 'Localhost' );
END IF
This is to support some legacy code and might not be the best solution to the problem. However, it will fix it for what I need.
Since I am getting lots of syntax errors on the answers, here is the exact version I have: Server version: 5.5.60-MariaDB MariaDB Server.
You can access Information Schema, to check if the table exists or not. Also, you will need to use Dynamic SQL (to handle the case when table name does not exist)
Try something like below:
IF EXISTS (SELECT 1
FROM information_schema.tables
WHERE table_schema = 'your_database_name'
AND table_name = 'OOK') THEN
SET #s1 = 'DELETE FROM your_database_name.OOK WHERE Id = ?';
SET #a = 'Development';
PREPARE stmt1 FROM #s1;
EXECUTE stmt1 USING #a;
DEALLOCATE PREPARE stmt1;
SET #s2 = 'INSERT INTO your_database_name.OOK VALUES (?, ?)';
SET #b = 'Development';
SET #c = 'Localhost';
PREPARE stmt2 FROM #s2;
EXECUTE stmt1 USING #b, #c;
DEALLOCATE PREPARE stmt2;
END IF
I use the procedure and the function below in a table duplication process in a db:
Usage
CALL do_something('mydb', 'OOK', 'Development', 'Development', 'Localhost');
Implementation
DELIMITER $$;
CREATE PROCEDURE do_something(
IN dbName VARCHAR(255),
IN tableName VARCHAR(255),
IN id VARCHAR(255),
IN value1 VARCHAR(255),
IN value2 VARCHAR(255)
)
BEGIN
IF ( fn_table_exists(dbName, tableName) )
THEN
CALL statement(CONCAT(
'DELETE FROM ', tableName, ' WHERE Id = "', id, '"'));
CALL statement(CONCAT(
'INSERT INTO ', tableName, ' VALUES ( "', value1, '", "', value2, '" )'));
ELSE
SELECT CONCAT(
'ERROR: Table "', tableName, '" does not exist in the schema "', dbName, '".'
) AS ErrorMessage;
END IF;
END$$
DELIMITER ;
DELIMITER $$;
CREATE PROCEDURE statement(IN dynamic_statement TEXT)
BEGIN
SET #dynamic_statement := dynamic_statement;
PREPARE prepared_statement FROM #dynamic_statement;
EXECUTE prepared_statement;
DEALLOCATE PREPARE prepared_statement;
END$$
DELIMITER ;
DELIMITER $$;
CREATE FUNCTION fn_table_exists(dbName VARCHAR(255), tableName VARCHAR(255))
RETURNS TINYINT(1)
BEGIN
DECLARE totalTablesCount INT DEFAULT (
SELECT COUNT(*)
FROM information_schema.TABLES
WHERE (TABLE_SCHEMA COLLATE utf8_general_ci = dbName COLLATE utf8_general_ci)
AND (TABLE_NAME COLLATE utf8_general_ci = tableName COLLATE utf8_general_ci)
);
RETURN IF(
totalTablesCount > 0,
TRUE,
FALSE
);
END$$
DELIMITER ;

Error when calling a SP from another one

I have created the following MySQL SP successfully..
CREATE DEFINER=`root`#`%` PROCEDURE `Common_Proc_Create_NewId`
(
TableName VARCHAR(250),
ColumnName VARCHAR(150),
OUT ReturnId BIGINT
)
BEGIN
DECLARE varb BIGINT;
SET #NewId:= CONCAT('SELECT (IFNULL(MAX(', ColumnName, '), 0) + 1) INTO ', varb, ' FROM ', TableName);
PREPARE Stmnt FROM #NewId;
EXECUTE Stmnt;
DEALLOCATE PREPARE Stmnt;
SET ReturnId = varb;
END$$
But when this was called from another SP I got the following error:
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 'NULL' at line 1
Calling SP
CREATE DEFINER=`root`#`%` PROCEDURE `Masters_Proc_Create_BranchType`(
BranchTypName VARCHAR(100)
)
BEGIN
CALL Common_Proc_Create_NewId('Masters_BranchType', 'BranchTypeId', #Id);
INSERT INTO Masters_BranchType (BranchTypeId, BranchTypeName) VALUES (#Id, BranchTypName);
SELECT #Id;
END$$
In your stored procedure Common_Proc_Create_NewId the part into varb was causing the issue and think it's not allowed that way in a prepared statement (not sure though). Instead the way you are doing, try like below and it works fine (a sample code included)
delimiter //
CREATE PROCEDURE dynamic1(IN tbl VARCHAR(64), IN col VARCHAR(64), OUT ret int)
BEGIN
SET #s = CONCAT('SELECT #i := (IFNULL(MAX(', col, '), 0) + 1) FROM ', tbl);
PREPARE stmt FROM #s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
set ret = #i;
END
//
delimiter ;
call dynamic1('test1','col',#id);
select #id;

MYSql Stored procedure Debug Query

When I try to run the mysql stored procedure code on phpmyadmin then error is generating .
The ERROR is : Syntax error near concat(strWhere, ' AND (qxt.topic_id IN (',
Thanks!
DELIMITER $$
DROP PROCEDURE IF EXISTS PercentageCalc$$
CREATE PROCEDURE PercentageCalc(topicArray VARCHAR(255),topicIndId int(11),userId VARCHAR(255),userArraySize int(11))
BEGIN
DECLARE x INT;
SET x = 0;
SELECT topicArray;
SELECT topicIndId;
SET #sql = CONCAT('SELECT COUNT(*) AS total FROM answer as ans
INNER JOIN question AS qst ON ans.question_id = qst.question_id
INNER JOIN question_topic AS qxt ON qxt.question_id = qst.question_id
WHERE (ans.answer_correct_flag = \'yes\')
AND (qxt.topic_id IN (\',topicArray,\'))',strwhere);
IF (topicIndId NOT NULL) THEN
SET strWhere = concat(strWhere, ' AND (qxt.topic_id IN (',topicIndId,'))');
END IF;
IF (userId NOT NULL) THEN
REPEAT
SET strWhere = concat(strWhere, ' AND (ans.user_id IN (',userId[X],'))');
SET x = x + 1;
UNTIL x > userArraySize
END REPEAT
END IF;
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
CALL PercentageCalc('1,2,3','1,2','1','1');

Error in Converting SQL Server stored procedure to Mysql

I am trying to convert a SQL Server stored procedure to Mysql as I am migrating an entire database to Mysql
But I am not able to convert a few of the stored procedures which are using XML interaction. I am not a Mysql guy. So could some one please help me out?
Thanks in advance.
My stored procedure in SQL Server looks like this:
ALTER PROCEDURE [dbo].[usp_MemberToDoList_UpdateForMember]
(
#xml nvarchar(max),
#login varchar(255)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #doc int;
DECLARE #now datetime = GETUTCDATE();
EXEC [sp_xml_preparedocument] #doc OUTPUT, #xml;
UPDATE
[mtdl]
SET
[taskCompleteDate] = CASE WHEN [isCompleted] = CONVERT(bit, 1) THEN #now ELSE NULL END,
[updatedBy] = #login,
[dateUpdated] = GETUTCDATE()
FROM
[MemberToDoList] [mtdl]
JOIN
OPENXML (#doc, '/todos/todo') WITH
(
[id] int,
[isCompleted] bit
) [x] ON [x].[id] = [mtdl].[memberToDoListId];
EXEC [sp_xml_removedocument] #doc;
END
When I convert to Mysql it looks like
CREATE PROCEDURE `conversion`.`usp_MemberToDoList_UpdateForMember` (xml longtext,
login varchar(255))
BEGIN
DECLARE v_doc int;
DECLARE v_now datetime(3);
set v_now = UTC_TIMESTAMP();
CALL sp_xml_preparedocument(#doc)
PREPARE stmt FROM #stmt_str;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
v_doc OUT, xml;
UPDATE
mtdl
SET
`taskCompleteDate` = CASE WHEN `isCompleted` = CONVERT(1,UNSIGNED) THEN v_now ELSE NULL END
,`updatedBy` = #login,
`dateUpdated` = UTC_TIMESTAMP()
FROM
`MemberToDoList` `mtdl`
JOIN
ExtractValue(#doc, '/todos/todo') WITH
(
`id` int,
`isCompleted` bit
) `x` ON [x].[id] = `mtdl`.`memberToDoListId`;
SET #stmt_str = `sxml_removedocument`;
PREPARE stmt FROM #stmt_str;
EXECUTE stmt;`enter code here`
DEALLOCATE PREPARE stmt; #doc;
END
but keeps me giving error:
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 'END' at line 1
FYI I am using Mysql version 5.6
try this:
your creating nor sql query, if you wants to create the sql procedure you should must add the delimiter in the starting and ending in your query. And ; add the like my query END; as query is following as:
delimiter //
CREATE PROCEDURE `conversion`.`usp_MemberToDoList_UpdateForMember` (xml longtext,
login varchar(255))
BEGIN
DECLARE v_doc int;
DECLARE v_now datetime(3);
set v_now = UTC_TIMESTAMP();
CALL sp_xml_preparedocument(#doc)
PREPARE stmt FROM #stmt_str;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
v_doc OUT, xml;
UPDATE
mtdl
SET
`taskCompleteDate` = CASE WHEN `isCompleted` = CONVERT(1,UNSIGNED) THEN v_now ELSE NULL END
,`updatedBy` = #login,
`dateUpdated` = UTC_TIMESTAMP()
FROM
`MemberToDoList` `mtdl`
JOIN
ExtractValue(#doc, '/todos/todo') WITH
(
`id` int,
`isCompleted` bit
) `x` ON [x].[id] = `mtdl`.`memberToDoListId`;
SET #stmt_str = `sxml_removedocument`;
PREPARE stmt FROM #stmt_str;
EXECUTE stmt;`enter code here`
DEALLOCATE PREPARE stmt; #doc;
END; //
delimiter ;
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html