0

Hello everybody.
I'd like some help with a query.

I have a database named 'base1' which contains many tables.
Some of the tables have names like 'track1' , 'track2' etc... which have identical columns.

I would like to select all the tables beginning with track and show the data of a specific column named 'ammount'.

Thanks in advance.

3
Contributors
4
Replies
6
Views
7 Years
Discussion Span
Last Post by ktsangop
0

Maybe you can use this:

(SELECT ammount FROM track1) UNION (SELECT ammount FROM track2) UNION (SELECT ammount FROM track3)
0

Thanks for the answers.
It seems like i have to use cursors which i am not familiar with but it is time for me to learn..

The following code

(SELECT ammount FROM track1) UNION (SELECT ammount FROM track2) UNION (SELECT ammount FROM track3)

requires that you know which tables you have to select. I want it to be dynamic cause the number of tables beginning with 'track' changes all the time.

I found that this returns the tables i want to use :

SELECT table_name FROM INFORMATION_SCHEMA.tables WHERE table_name LIKE 'track%'

Now i am trying to find a way to execute a query seperately in all of the tables the first line returns and join the results.

0

Can someone find my error on the following code?
On execution i get the error :
Table 'base1.tablename' doesn't exist

CREATE DEFINER=`root`@`localhost` PROCEDURE `proc5`()
BEGIN
  DECLARE done BOOL DEFAULT FALSE;
  DECLARE tablename VARCHAR (20);
  DECLARE tracktables CURSOR FOR
  SELECT table_name FROM INFORMATION_SCHEMA.tables WHERE table_name LIKE 'track%';
  DECLARE CONTINUE HANDLER FOR SQLSTATE '02000'
    SET done = TRUE;

  OPEN tracktables;

  myloop: LOOP
    FETCH tracktables INTO tablename;
    IF done THEN
      CLOSE tracktables;
      LEAVE myloop;
    END IF;

    SELECT ammount from tablename;
  END LOOP;
END

I suppose that my usage of tablename cursor isn't correct but how should i use it?

Thanks in advance..

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.