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;
Related
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');
I want to call a dynamic procedure with a particular time_stamp and pro_id.
In the first step I want to find out if that particular pro_id exists in the table. Is there anything wrong in the Concat statement? I do not get the desired OUT value
DELIMITER ;;
CREATE PROCEDURE 'ADDCONSENSUS'(IN time_stamp int(10), IN pro_id INT(10), OUT cnt INT(11))
BEGIN
SET #sql1 = CONCAT('SELECT COUNT(pid) INTO #cnt FROM ',time_stamp,' WHERE pid = ,pro_id);
PREPARE stmt from #sql1;
EXECUTE stmt;
END
You can try the following:
DELIMITER $$
DROP PROCEDURE IF EXISTS `ADDCONSENSUS`$$
CREATE PROCEDURE `ADDCONSENSUS`(
IN `time_stamp` INT,
IN `pro_id` INT,
OUT `cnt` INT)
BEGIN
SET #sql1 := CONCAT('
SELECT COUNT(`pid`) INTO #`cnt`
FROM `', CAST(`time_stamp` AS CHAR), '`
WHERE `pid` = ', CAST(`pro_id` AS CHAR));
PREPARE stmt FROM #sql1;
EXECUTE stmt;
SET `cnt` := #`cnt`;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
CALL `ADDCONSENSUS`(1395395302, 3, #`_count`);
SQL Fiddle demo
I have a procedure call that updates a set of data and then returns the data set for my to render. Everything works fine except that, I cant do both operations at once. If I do the update, then the procedure, won´t return any value and vice versa. I have seen some answers suggesting to use temptables but I could not find how to retrieve the dataset. I appreciate any help even if it comes to improving my query.
CREATE DEFINER=`root`#`localhost` PROCEDURE `prueba`(IN `idUsuario` INT)
MODIFIES SQL DATA
BEGIN
DECLARE flag INT DEFAULT FALSE;
DECLARE done INT DEFAULT FALSE;
DECLARE idNotificacion INT DEFAULT 0;
DECLARE cont INT DEFAULT 0;
DECLARE resultset CURSOR FOR SELECT id FROM notificaciones WHERE involvedA_idUsuario=idUsuario AND active=1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN resultset;
SET #query = "SELECT * FROM notificaciones n WHERE n.id IN('null'";
the_loop: LOOP
FETCH resultset INTO idNotificacion;
IF done THEN
LEAVE the_loop;
END IF;
SET cont = cont + 1;
SET flag = TRUE;
SET #query = CONCAT(#query," , " ,idNotificacion);
UPDATE notificaciones SET active=0 WHERE id=idNotificacion;
END LOOP the_loop;
CLOSE resultset;
IF flag THEN
SET #query = CONCAT(#query, ")");
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END
Do you really need a cursor? An option like this, maybe it can be useful:
/* Procedure structure for procedure `prueba` */
/*!50003 DROP PROCEDURE IF EXISTS `prueba` */;
DELIMITER $$
CREATE PROCEDURE `prueba`(`idusuario` INT)
BEGIN
DECLARE `ids` LONGTEXT DEFAULT NULL;
SELECT GROUP_CONCAT(`id`) INTO `ids`
FROM `notificaciones`
WHERE `involveda_idusuario` = `idusuario` AND `active` = 1;
IF (`ids` IS NOT NULL) THEN
SET #`stmt` := CONCAT('UPDATE `notificaciones`
SET `active` = 0
WHERE `id` IN (', `ids`, ')');
PREPARE `exec` FROM #`stmt`;
EXECUTE `exec`;
SET #`stmt` := CONCAT('SELECT `id`, `involveda_idusuario`, `active`
FROM `notificaciones` `n`
WHERE `n`.`id` IS NULL OR `n`.`id` IN (', `ids`, ')');
PREPARE `exec` FROM #`stmt`;
EXECUTE `exec`;
DEALLOCATE PREPARE `exec`;
END IF;
END$$
DELIMITER ;
You must be careful with GROUP_CONCAT and the system variable group_concat_max_len.
SQL Fiddle demo
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 ;
1)Below is the code I'm trying for a procedure where I need to compare the count from two different tables. (tbl1 and tbl2 are in parameters to be passed).
But in the above code the values for 'a' and 'b' are set as statements. I need the resultant value(count) from the two statements to compare in the 'IF' condition.
declare a integer;
declare b integer;
set #a:=concat('select count(*) from ', tbl1);
/*PREPARE stmt1 FROM #a;
execute stmt1;
deallocate PREPARE stmt1;*/
set #b:= concat('select count(*) from ', tbl2);
/*PREPARE stmt2 FROM #b;
execute stmt2;
deallocate PREPARE stmt2;*/
if
#a=#b
then
select 1;
else
select 2;
end if;
2) Actually where I am facing a problem to set 'tbl1' and 'tbl2' as parameters in procedure.
The below code works fine if the table names are given directly, but i need them as parameters.
CREATE PROCEDURE myproc (in tbl1 varchar(50), in tbl2 varchar(50))
declare a integer;
declare b integer;
set #a:=(select count(*) from tbl1);
/*PREPARE stmt1 FROM #a;
execute stmt1;
deallocate PREPARE stmt1;*/
set #b:= (select count(*) from tbl2);
/*PREPARE stmt2 FROM #b;
execute stmt2;
deallocate PREPARE stmt2;*/
if
#a=#b
then
select 1;
else
select 2;
end if;
Hope anyone out there can help me with the solution.
As mentioned in the comments above, it is likely that you shouldn't be doing this at all... but, for what it's worth:
SET #sql := CONCAT('SELECT (
SELECT COUNT(*) FROM `',REPLACE('`','``',tbl1),'`
) = (
SELECT COUNT(*) FROM `',REPLACE('`','``',tbl2),'`
);');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET #sql := NULL;
REPLACE() has been used to try and avoid SQL injection (it's somewhat crude, but it's the best one can do without further information).