MYSQL - SELECT data from dynamic table names - mysql

Imagine that I have several dynamic table names such as :
select table_name
from INFORMATION_SCHEMA.TABLES
where table_name like 'ifhcraw%';
ifhcraw_2016_03_25_13
ifhcraw_2016_03_26_19
ifhcraw_2016_03_28_2
And I don't found any rule on names. To find last edited table I have just select last modified table with query :
select table_name
from INFORMATION_SCHEMA.TABLES
where table_name like 'ifhcraw%' and
update_time = (select max(update_time)
from INFORMATION_SCHEMA.TABLES
where table_name like 'ifhcraw%');
Now the purpose all of this step to get data from table_name.
I have tried to use variables , however it was failed. For example :
SET #query1 := 'select table_name
from INFORMATION_SCHEMA.TABLES
where table_name like \'ifhcraw%\' and
update_time = (select max(update_time)
from INFORMATION_SCHEMA.TABLES
where table_name like \'ifhcraw%\') ';
SET #query2 := concat('select *
from ', #query1);
PREPARE stmt from #query2;
execute stmt;
Please help to solve issue.

Try:
mysql> SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.7.11 |
+-----------+
1 row in set (0.00 sec)
mysql> DROP TABLE IF EXISTS `ifhcraw_2016_03_25_13`;
Query OK, 0 rows affected (0.00 sec)
mysql> DROP TABLE IF EXISTS `ifhcraw_2016_03_26_19`;
Query OK, 0 rows affected (0.00 sec)
mysql> DROP TABLE IF EXISTS `ifhcraw_2016_03_28_2`;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE `ifhcraw_2016_03_25_13` (
-> `id` INT
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE `ifhcraw_2016_03_26_19` (
-> `id` INT
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE `ifhcraw_2016_03_28_2` (
-> `id` INT
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> SET #`TABLE_NAME` := NULL;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT `TABLE_NAME` INTO #`TABLE_NAME`
-> FROM `INFORMATION_SCHEMA`.`TABLES`
-> WHERE `TABLE_NAME` LIKE 'ifhcraw%' AND
-> `UPDATE_TIME` = (SELECT MAX(`UPDATE_TIME`)
-> FROM `INFORMATION_SCHEMA`.`TABLES`
-> WHERE `TABLE_NAME` LIKE 'ifhcraw%'
-> );
Query OK, 0 rows affected, 1 warning (0.01 sec)
mysql> SELECT #`TABLE_NAME`;
+---------------+
| #`TABLE_NAME` |
+---------------+
| NULL |
+---------------+
1 row in set (0.00 sec)
mysql> SET #`qry` := IF(#`TABLE_NAME` IS NULL,
-> 'SELECT NULL',
-> CONCAT('SELECT * FROM ', #`TABLE_NAME`));
Query OK, 0 rows affected (0.00 sec)
mysql> PREPARE `stmt` FROM #`qry`;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE `stmt`;
+------+
| NULL |
+------+
| NULL |
+------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE `stmt`;
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO `ifhcraw_2016_03_26_19`
-> (`id`)
-> VALUES
-> (1);
Query OK, 1 row affected (0.00 sec)
mysql> SELECT `TABLE_NAME` INTO #`TABLE_NAME`
-> FROM `INFORMATION_SCHEMA`.`TABLES`
-> WHERE `TABLE_NAME` LIKE 'ifhcraw%' AND
-> `UPDATE_TIME` = (SELECT MAX(`UPDATE_TIME`)
-> FROM `INFORMATION_SCHEMA`.`TABLES`
-> WHERE `TABLE_NAME` LIKE 'ifhcraw%'
-> );
Query OK, 1 row affected (0.00 sec)
mysql> SELECT #`TABLE_NAME`;
+-----------------------+
| #`TABLE_NAME` |
+-----------------------+
| ifhcraw_2016_03_26_19 |
+-----------------------+
1 row in set (0.00 sec)
mysql> SET #`qry` := IF(#`TABLE_NAME` IS NULL,
-> 'SELECT NULL',
-> CONCAT('SELECT * FROM ', #`TABLE_NAME`));
Query OK, 0 rows affected (0.00 sec)
mysql> PREPARE `stmt` FROM #`qry`;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE `stmt`;
+------+
| id |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE `stmt`;
Query OK, 0 rows affected (0.00 sec)
UPDATE
Care should be taken when there are two or more tables that match the criteria, will fail as follows:
mysql> INSERT INTO `ifhcraw_2016_03_26_19`
-> (`id`)
-> VALUES
-> (1);
Query OK, 1 row affected (0,00 sec)
mysql> INSERT INTO `ifhcraw_2016_03_28_2`
-> (`id`)
-> VALUES
-> (1);
Query OK, 1 row affected (0,00 sec)
mysql> SELECT `TABLE_NAME`
-> FROM `INFORMATION_SCHEMA`.`TABLES`
-> WHERE `TABLE_NAME` LIKE 'ifhcraw%' AND
-> `UPDATE_TIME` = (SELECT MAX(`UPDATE_TIME`)
-> FROM `INFORMATION_SCHEMA`.`TABLES`
-> WHERE `TABLE_NAME` LIKE 'ifhcraw%'
-> );
+-----------------------+
| TABLE_NAME |
+-----------------------+
| ifhcraw_2016_03_26_19 |
| ifhcraw_2016_03_28_2 |
+-----------------------+
2 rows in set (0,00 sec)
mysql> SELECT `TABLE_NAME` INTO #`TABLE_NAME`
-> FROM `INFORMATION_SCHEMA`.`TABLES`
-> WHERE `TABLE_NAME` LIKE 'ifhcraw%' AND
-> `UPDATE_TIME` = (SELECT MAX(`UPDATE_TIME`)
-> FROM `INFORMATION_SCHEMA`.`TABLES`
-> WHERE `TABLE_NAME` LIKE 'ifhcraw%'
-> );
ERROR 1172 (42000): Result consisted of more than one row
You should handle the case as you deem appropriate.

Related

Mysql Error #1064 near Null in call stored procedure with out param

I'm quite new with MySQL. I have to call a stored procedure with output param. I've searched a lot on internet but I've not found the correct solution to my problem. If I call the stored procedure with the #outputParamName it says that I have an error #1064 near NULL. If I call the procedure with the 'outputParamName' without the # it says thath it is not an OUT or INOUT correct param. Someone can help me please?
the stored procedure just have to check if surname and name in DB exists on the same row:
CREATE PROCEDURE InsertProc (INOUT existsInDb BOOLEAN,
IN dbName VARCHAR(50)
IN tableName VARCHAR(50)
IN surnameNew VARCHAR(50)
IN nameNew VARCHAR(50))
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
BEGIN
DECLARE rowSurnameName int;
SET #sqlSel = CONCAT('SELECT COUNT(*) INTO ', rowSurnameName, ' FROM ', dbName, '.', tableName, ' WHERE COGNOME=', surnameNew, ' AND NOME=', nameNew);
PREPARE stmtSel FROM #sqlSel;
EXECUTE stmtSel;
DEALLOCATE PREPARE stmtSel;
IF (rowSurnameName=0) THEN
SET #sqlIns = CONCAT('INSERT INTO ', dbName, '.', tableName, ' (NOME, COGNOME) VALUES (', nameNew, ', ', surnameNew,')');
PREPARE stmtIns FROM #sqlIns;
EXECUTE stmtIns;
DEALLOCATE PREPARE stmtIns;
SELECT false INTO existsInDb;
ELSE SELECT true INTO existsInDb;
END IF;
END
The CALL Statement is:
SET #dbName = 'DBNAME';
SET #tableName = 'DBTABLE';
SET #surname = 'SURNAME';
SET #name = 'NAME';
PREPARE s FROM 'CALL InsertProc(?,?,?,?,?)';
EXECUTE s USING #existsInDB, #dbName, #tableName, #surname, #name;
SELECT #existsInDB;
And the ERROR Line is:
#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
A couple of notes:
You can't use a local variable in a prepared statement.
C.1 Restrictions on Stored Programs
...
SELECT ... INTO local_var cannot be used as a prepared statement.
...
The error shown in your question occurs because the local variable rowSurnameName has the value NULL, see:
mysql> DROP PROCEDURE IF EXISTS `InsertProc`;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> DELIMITER //
mysql> CREATE PROCEDURE `InsertProc`()
-> BEGIN
-> DECLARE `rowSurnameName` INT;
-> SELECT `rowSurnameName`;
-> SET #`sqlSel` := CONCAT('SELECT COUNT(*) INTO ', `rowSurnameName`);
-> SELECT #`sqlSel`;
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql> CALL `InsertProc`;
+------------------+
| `rowSurnameName` |
+------------------+
| NULL |
+------------------+
1 row in set (0.00 sec)
+-----------+
| #`sqlSel` |
+-----------+
| NULL |
+-----------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
If you try to use the rowSurnameName local variable in the prepared statement, you will get the error:
mysql> DROP PROCEDURE IF EXISTS `InsertProc`;
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER //
mysql> CREATE PROCEDURE `InsertProc`()
-> BEGIN
-> DECLARE `rowSurnameName` INT;
-> SET #`sqlSel` := CONCAT('SELECT 100 INTO `rowSurnameName`');
-> SELECT #`sqlSel`;
-> PREPARE `stmtSel` FROM #`sqlSel`;
-> EXECUTE `stmtSel`;
-> DEALLOCATE PREPARE `stmtSel`;
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql> CALL `InsertProc`;
+----------------------------------+
| #`sqlSel` |
+----------------------------------+
| SELECT 100 INTO `rowSurnameName` |
+----------------------------------+
1 row in set (0.00 sec)
ERROR 1327 (42000): Undeclared variable: rowSurnameName
You need to use 9.4 User-Defined Variables in your prepared statement:
mysql> DROP PROCEDURE IF EXISTS `InsertProc`;
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER //
mysql> CREATE PROCEDURE `InsertProc`()
-> BEGIN
-> SET #`sqlSel` := CONCAT('SELECT 100 INTO #`rowSurnameName`');
-> SELECT #`sqlSel`;
-> PREPARE `stmtSel` FROM #`sqlSel`;
-> EXECUTE `stmtSel`;
-> DEALLOCATE PREPARE `stmtSel`;
-> IF (#`rowSurnameName` = 0) THEN
-> SELECT 'NotExistsInDbAndInsert';
-> ELSE
-> SELECT 'existsInDb';
-> END IF;
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql> CALL `InsertProc`;
+-----------------------------------+
| #`sqlSel` |
+-----------------------------------+
| SELECT 100 INTO #`rowSurnameName` |
+-----------------------------------+
1 row in set (0.00 sec)
+------------+
| existsInDb |
+------------+
| existsInDb |
+------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

Calling a procedure from a procedure

I'm trying to call a procedure inside procedure, however the calling procedure is in a different db schema so it's a variable and isn't translating.
DECLARE client_database varchar(255);
SET client_database = get_database(_client_id); --this gets the schema the procedure is in
CALL client_database.client_procedure(); --then trying to call the procedure with the db schema variable however it's not translating
Question: Why isn't client_database translating?
One option is to use a 13.5 Prepared SQL Statement Syntax:
mysql> DROP PROCEDURE IF EXISTS `client_procedure`;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> DROP PROCEDURE IF EXISTS `server_procedure`;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> DROP DATABASE IF EXISTS `client_db`;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> DROP DATABASE IF EXISTS `server_db`;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> CREATE DATABASE IF NOT EXISTS `client_db`;
Query OK, 1 row affected (0.00 sec)
mysql> CREATE DATABASE IF NOT EXISTS `server_db`;
Query OK, 1 row affected (0.00 sec)
mysql> DELIMITER //
mysql> CREATE PROCEDURE `client_db`.`client_procedure`()
-> BEGIN
-> SELECT CONCAT('FROM `', DATABASE(), '`');
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE PROCEDURE `server_db`.`controller_procedure`()
-> BEGIN
-> DECLARE `client_database` VARCHAR(64);
->
-> -- This gets the schema the procedure is in
-> -- SET `client_database` := `get_database`(`client_id`);
-> SET `client_database` := 'client_db';
->
-> SET #`call` := CONCAT('CALL `', `client_database`, '`.`client_procedure`');
-> PREPARE `stmt` FROM #`call`;
-> EXECUTE `stmt`;
-> DEALLOCATE PREPARE `stmt`;
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql> CALL `server_db`.`controller_procedure`;
+-----------------------------------+
| CONCAT('FROM `', DATABASE(), '`') |
+-----------------------------------+
| FROM `client_db` |
+-----------------------------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
See db-fiddle.

mysql Transaction in the commit block

CREATE DEFINER=`root`#`localhost` PROCEDURE `PrcCopyQuestion_Admin`(in Param1,in Param2 varchar(45))
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
Select 'Fail' as 'Status' ;
END;
DECLARE EXIT HANDLER FOR sqlwarning
BEGIN
ROLLBACK;
Select 'Fail' as 'Status' ;
END;
Start transaction;
Insert statement 1;
Insert statement 2;
SELECT 'Success' AS 'Status';
call PrcGetQuestionAndOption_Admin(#variable);
Commit;
END
I am using Mysql 5.7. When in the commit block if the second (Insert statement 2) fails. It will go in the Rollback part and gives me output as 'Failed'. But when i am getting the output it still executes the Select 'Success' as Status in commit block.
So my question is when the second insert statement fails. It should go directly in rollback and give me status as fail. It should not execute the status as 'success' in commit block.
Eg: On rollback I am getting two result set:
Select 'Fail'..1st result set
Select 'Success'....2nd result set
I need output as only
Select 'fail'
Any help appreciated!!
I can't reproduce the problem.
mysql> SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.7.12 |
+-----------+
1 row in set (0.00 sec)
mysql> DROP TABLE IF EXISTS `t1`, `t2`;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `t1` (
-> `c0` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `t2` (
-> `c0` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER //
mysql> DROP PROCEDURE IF EXISTS `PrcCopyQuestion_Admin`//
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE PROCEDURE `PrcCopyQuestion_Admin`(Param1 INT, Param2 VARCHAR(45))
-> BEGIN
-> DECLARE EXIT HANDLER FOR SQLEXCEPTION
-> BEGIN
-> ROLLBACK;
-> SELECT 'Fail' Status;
-> END;
-> DECLARE EXIT HANDLER FOR SQLWARNING
-> BEGIN
-> ROLLBACK;
-> SELECT 'Fail' Status;
-> END;
-> START TRANSACTION;
-> INSERT INTO `t1` (`c0`) VALUES (0);
-> IF Param1 = 0 THEN
-> INSERT INTO `ERR_t2` (`c0`) VALUES (0);
-> ELSE
-> INSERT INTO `t2` (`c0`) VALUES (0);
-> END IF;
-> SELECT 'Success' Status;
-> COMMIT;
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql> CALL `PrcCopyQuestion_Admin`(0, NULL);
+--------+
| Status |
+--------+
| Fail |
+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT
-> `c0`
-> FROM
-> `t1`;
Empty set (0.00 sec)
mysql> SELECT
-> `c0`
-> FROM
-> `t2`;
Empty set (0.00 sec)
mysql> CALL `PrcCopyQuestion_Admin`(1, NULL);
+---------+
| Status |
+---------+
| Success |
+---------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT
-> `c0`
-> FROM
-> `t1`;
+----+
| c0 |
+----+
| 2 |
+----+
1 row in set (0.00 sec)
mysql> SELECT
-> `c0`
-> FROM
-> `t2`;
+----+
| c0 |
+----+
| 1 |
+----+
1 row in set (0.00 sec)

Prepared statement needs to be re-prepared in mysql

I'm trying to access data from view and insert into a temptable, inside a store procedure, below is the store procedure .
When I try to execute the sp I'm getting "Prepared statement needs to be re-prepared" error.
Can some one pls suggest how to fix this error in mysql.
Procedure:
DROP PROCEDURE IF EXISTS getFilteredData;
CREATE PROCEDURE getFilteredData()
BEGIN
DECLARE sql2 VARCHAR(5000);
DROP TEMPORARY TABLE IF EXISTS TempTbl;
CREATE TEMPORARY TABLE TempTbl
(
ID VARCHAR(50),
Name VARCHAR(500),
Status INT
);
SET sql2 = 'INSERT INTO TempTbl Select ID,Name,Id as Status from v_release;';
SET #SWV_Stmt = sql2;
PREPARE SWT_Stmt FROM #SWV_Stmt;
EXECUTE SWT_Stmt;
DEALLOCATE PREPARE SWT_Stmt;
SELECT * FROM TempTbl;
END;
I can't reproduce the problem that you report.
mysql> SELECT VERSION();
+-----------------+
| VERSION() |
+-----------------+
| 5.5.22-0ubuntu1 |
+-----------------+
1 row in set (0.00 sec)
mysql> DELIMITER //
mysql> DROP TABLE IF EXISTS `release`//
Query OK, 0 rows affected (0.00 sec)
mysql> DROP VIEW IF EXISTS `v_release`//
Query OK, 0 rows affected (0.00 sec)
mysql> DROP PROCEDURE IF EXISTS `getFilteredData`//
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE `release` (
-> `id` VARCHAR(50),
-> `name` VARCHAR(500),
-> `status` INT
-> )//
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE VIEW `v_release` AS
-> SELECT `id`, `name`, `status`
-> FROM `release`//
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO `release`
-> (`id`, `name`, `status`)
-> VALUES
-> ('1', 'NAME1', 1),
-> ('2', 'NAME2', 2),
-> ('3', 'NAME1', 3)//
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> CREATE PROCEDURE `getFilteredData`()
-> BEGIN
-> DROP TEMPORARY TABLE IF EXISTS `temptbl`;
-> CREATE TEMPORARY TABLE `temptbl` (
-> `id` VARCHAR(50),
-> `name` VARCHAR(500),
-> `status` INT);
-> PREPARE `stmt` FROM 'INSERT INTO `temptbl`
'> SELECT `id`, `name`, `status`
'> FROM `v_release`';
-> EXECUTE `stmt`;
-> DEALLOCATE PREPARE `stmt`;
-> SELECT `id`, `name`, `status`
-> FROM `temptbl`;
-> DROP TEMPORARY TABLE IF EXISTS `temptbl`;
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql> CALL `getFilteredData`;
+------+-------+--------+
| id | name | status |
+------+-------+--------+
| 1 | NAME1 | 1 |
| 2 | NAME2 | 2 |
| 3 | NAME1 | 3 |
+------+-------+--------+
3 rows in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
SQL Fiddle demo

Run a query in a MySQL stored procedure if a condition is true

I am using MySQL database and trying to create a stored procedure. How can I make it so that if the result of query1 has no records, then it execute a different query?
Here is what I have so far:
/* CREATE DB */
CREATE DATABASE mydata;
use mydata;
/* TABLE */
CREATE TABLE mydata (
ID BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(255) NOT NULL,
Value VARCHAR(255) NOT NULL
) ENGINE=InnoDB;
INSERT INTO mydata (Name, Value) VALUES ("testname", "testvalue");
/* STORED PROCEDURE */
delimiter //
CREATE PROCEDURE myproc(IN myTable VARCHAR(255),
IN myValue VARCHAR(255),
IN myValueTwo VARCHAR(255))
BEGIN
SET #iTable=myTable;
SET #iValue=myValue;
SET #iValueTwo=myValueTwo;
SET #query = CONCAT('SELECT Name FROM ', #iTable,
' WHERE Value="', #iValue, '"');
SET #querytwo = CONCAT('SELECT Name FROM ', #iTable,
' WHERE Value="', #iValueTwo, '"');
PREPARE QUERY FROM #query;
EXECUTE QUERY;
END //
delimiter ;
/* CALL */
call myproc("mydata", "testvalue", "");
I want to run a query, and execute a secondary query only if the first has no rows. What is the best way to do this?
This took some work but I made enough adjustments. The problem with your code has nothing to do with your logic but with MySQL Stored Procedure Language itself. When doing dynamic SQL It has scoping issues.
What I did was create a temp table and deposited the returned value in it
Here is some sample data loaded
mysql> drop database if exists user391986;
Query OK, 1 row affected (0.08 sec)
mysql> create database user391986;
Query OK, 1 row affected (0.00 sec)
mysql> use user391986
Database changed
mysql> CREATE TABLE mytable (
-> ID BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name VARCHAR(255) NOT NULL,
-> Value VARCHAR(255) NOT NULL
-> ) ENGINE=InnoDB;
Query OK, 0 rows affected (0.11 sec)
mysql> INSERT INTO mytable (Name,Value) VALUES
-> ('rolando','edge'),('pamela','washington'),
-> ('dominique','wilkins'),('diamond','cutter');
Query OK, 4 rows affected (0.06 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> SELECT * from mytable;
+----+-----------+------------+
| ID | Name | Value |
+----+-----------+------------+
| 1 | rolando | edge |
| 2 | pamela | washington |
| 3 | dominique | wilkins |
| 4 | diamond | cutter |
+----+-----------+------------+
4 rows in set (0.00 sec)
mysql>
Here is the stored procedure adjusted to catch the return values in a temp table
mysql> delimiter //
mysql> CREATE PROCEDURE myproc(IN myTable VARCHAR(255), IN myValue VARCHAR(255), IN myValueTwo VARCHAR(255))
-> BEGIN
-> DECLARE foundcount INT;
-> DECLARE retval VARCHAR(255);
->
-> SET #iTable=myTable;
-> SET #iValue=myValue;
-> SET #iValueTwo=myValueTwo;
->
-> CREATE TEMPORARY TABLE IF NOT EXISTS mynumber (rv VARCHAR(255)) ENGINE=MEMORY;
-> DELETE FROM mynumber;
->
-> SET retval = 'nothing retrieved';
-> SET #query = CONCAT('INSERT INTO mynumber SELECT Name FROM ', #iTable, ' WHERE Value=''', #iValue, '''');
-> PREPARE QUERY FROM #query;
-> EXECUTE QUERY;
-> DEALLOCATE PREPARE QUERY;
-> SELECT COUNT(1) INTO foundcount FROM mynumber;
-> IF foundcount = 0 THEN
-> SET #querytwo = CONCAT('INSERT INTO mynumber SELECT Name FROM ', #iTable, ' WHERE Value=''', #iValueTwo, '''');
-> PREPARE QUERY FROM #querytwo;
-> EXECUTE QUERY;
-> DEALLOCATE PREPARE QUERY;
-> END IF;
-> SELECT COUNT(1) INTO foundcount FROM mynumber;
-> IF foundcount > 0 THEN
-> SELECT rv INTO retval FROM mynumber;
-> END IF;
-> SELECT retval;
->
-> END //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql>
OK I called the stored procedure three time. The first gets nothing. The second gets the second value. The third gets the first value.
mysql> CALL myproc('mytable','pamela','diamond');
+-------------------+
| retval |
+-------------------+
| nothing retrieved |
+-------------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.02 sec)
mysql> CALL myproc('mytable','pamela','wilkins');
+-----------+
| retval |
+-----------+
| dominique |
+-----------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.01 sec)
mysql> CALL myproc('mytable','edge','wilkins');
+---------+
| retval |
+---------+
| rolando |
+---------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.02 sec)
mysql>
Give it a Try !!!
In mysql you can use the found_rows() built in procedure like this:
el#apollo:~$ mysql -u root -p
Enter password:
mysql> use your_database;
Database changed
mysql> select id from problems;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
+----+
4 rows in set (0.00 sec)
mysql> select found_rows();
+--------------+
| found_rows() |
+--------------+
| 4 |
+--------------+
1 row in set (0.00 sec)
In mssql you can use the value ##rowcount. Then you can run the second query only if the first query returned no rows:
EXECUTE QUERY;
IF ##rowcount = 0
BEGIN
PREPARE QUERY FROM #querytwo;
EXECUTE QUERY;
END
In Sql Server, you could run the results into a temporary table and then check the temp table for rows like this:
declare #numberResults int = 0
create table #MyTempTable(...)
insert #MyTempTable
sp_executesql Query
set #numberResults = (select count(*) from #MyTempTable)
if #numberResults = 0
begin
sp_executesql secondQuery
end
My simplest working code
BEGIN
IF test = 'null' THEN
PREPARE QUERY FROM 'SELECT username as name from login';
EXECUTE QUERY;
ELSE
PREPARE QUERY FROM 'SELECT username as name2 from login';
EXECUTE QUERY;
END IF;
END