user2459396
user2459396

Reputation: 95

Combine similar data from multiple schemas

I have a table in a common schema which contain details about all enterprises of the application like id, name, logo, web_site_address, schema_name etc. Then there are schemas for each enterprise sharing same data structure. Now there is a requirement to find some information for all enterprises. I have written the following query in a function to do this. However, I feel there must be a better way to do this without using a CREATE TEMP TABLE.
Any help refactoring this would be highly appreciated.

CREATE TEMPORARY TABLE IF NOT EXISTS temp_vehicles(plateno character varying, vehiclesurrogate_id bigint, devicesurrogate_id bigint, startdate  timestamp with time zone, enddate  timestamp with time zone);
    EXECUTE 'TRUNCATE TABLE temp_vehicles';

FOR r IN SELECT * FROM platformdb.entreprise_details LOOP
    EXECUTE 'SET SEARCH_PATH TO ' || r.schema_name || ', public';
    EXECUTE 'INSERT INTO temp_vehicles SELECT v.plateno, v.vehiclesurrogate_id, vda.devicesurrogate_id, vda.startdate, vda.enddate
                                FROM ' || r.schema_name || '.object_access_vehicle() v
                                INNER JOIN ' || r.schema_name || '.vehicledeviceassignment vda on vda.vehiclesurrogate_id = v.vehiclesurrogate_id AND overlap(startdate, enddate, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
                                INNER JOIN platformdb.lt_enterprise_device lted ON lted.device_surrogate_id = vda.devicesurrogate_id AND overlap(lted.startdate, lted.enddate, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) AND enterprise_surrogate_id = ' || r.entreprise_surrogate_id;
END LOOP;

Thanks,

Upvotes: 0

Views: 245

Answers (1)

Jayadevan
Jayadevan

Reputation: 1342

You can create a view which is a union of these tables and use that? Create view myview () as select ... from schema1.table1 union select ... from schema2.table2 union..

Upvotes: 1

Related Questions