I have a common situation that comes up where I want to join with a table moredata. To give the simplest example, imagine I have:
SELECT *
FROM x
JOIN moredata d on x.yyyymmdd = d.yyyymmdd
x
will vary while moredata
stays the same. What's a good way stylistically to reuse code, automate the above so that I can apply it to different tables (eg. do the same thing on table 'y' instead of 'x')?
One way would be to write a plpgsql function using dynamic SQL that operates on the name of the table. Something like:
CREATE FUNCTION joinmoredata(tblname text) RETURNS TABLE(...) AS $$
BEGIN
RETURN QUERY EXECUTE format('SELECT * FROM %I JOIN moredata on ...', tblname);
END;
$$ LANGUAGE plpgsql;
But then you couldn't apply it to a derived table or a CTE. Is there a better way? Or is dynamic SQL the best way to reuse code in this situation?
(Note, the actual query is a lot more complicated than SELECT * FROM x JOIN moredata d on x.yyyymmdd = d.yyyymmdd
which is why I want to reuse code.)