Postgresql Dynamic Table Access
Solution 1:
OK, I found a solution:
CREATEOR REPLACE FUNCTION getProductById(cid int) RETURNS RECORD AS $$
DECLAREresult RECORD;
BEGINEXECUTE'SELECT * FROM '|| (SELECT ('products.'|| (select category_name from category where category_id = cid) ||'_view')::regclass) INTOresult;
RETURNresult;
END;
$$ LANGUAGE plpgsql;
and to select:
SELECT * FROM getProductById(7) AS b(category_id int, ... );
works for PostgreSQL 9.x
Solution 2:
If you can change your database layout to use partitioning instead, that would probably be the way to go. Then you can just access the "master" table as if it were one table rather than multiple subtables.
You could create a view that combines the tables with an extra column corresponding to the table it's from. If all your queries specify a value for this extra column, the planner should be smart enough to skip scanning all the rest of the tables.
Or you could write a function in PL/pgSQL, using the EXECUTE command to construct the appropriate query after fetching the table name. The function can even return a set so it can be used in the FROM clause just as you would a table reference. Or you could just do the same query construction in your application logic.
Solution 3:
To me, it sounds like you've a major schema design problem: shouldn't you only have one products table with a category_id in it?
Might you be maintaining the website mentioned in this article?
http://thedailywtf.com/Articles/Confessions-The-Shopping-Cart.aspx
Post a Comment for "Postgresql Dynamic Table Access"