0

Below is what I am trying to achieve. I have a database 'CARS_DATABASE', wherein there are the following tables:

Lorries Vans Buses Convertibles City_cars Stretch_limos Rescue_vehicles Double_decker_buses

First of all, I am going to run the following query to get the list of the tables:

SELECT TableName
 FROM 
 (SELECT TableName
 FROM DBC.TablesV
 WHERE DatabaseName = 'CARS_DATABASE';

Now, I would like to incorporate it into one query which would look as follows:

Select count(*) from CARS_DATABASE.**TableName**
 WHERE TableName = (SELECT TableName
 FROM 
 (SELECT TableName
 FROM DBC.TablesV
 WHERE DatabaseName = 'CARS_DATABASE') Q1);

I wonder how I can make this dynamic and pass into FROM clause the names of all tables. Essentially, I would like it to select from all those tables dynamically, e.g.

Select count(*) from CARS_DATABASE.Lorries
Select count(*) from CARS_DATABASE.Vans
Select count(*) from CARS_DATABASE.Buses 

and so on.

Do I have to write a macro or stored procedure to achieve that?

Many thanks in advance for your suggestions.

Cheers Andy

Andy
  • 37
  • 1
  • 6

1 Answers1

0

Have a derived table (the subquery), where you SELECT and UNION ALL the different vehicle tables. GROUP BY the result.

select vehicle_type, count(*)
from
(
    select 'lorries' as vehicle_type from CARS_DATABASE.Lorries
    union all
    select 'vans' as vehicle_type from CARS_DATABASE.vans
    union all
    ...
    select 'Double_decker_buses' as vehicle_type from CARS_DATABASE.Double_decker_buses
) vehicles
GROUP BY vehicle_type 

Note: I'd store all vehicles in one common table. If you're stuck with separated tables, you could create a view to UNION ALL the different tables.

jarlh
  • 42,561
  • 8
  • 45
  • 63