问题
I'm writing a batch mode update function and at the moment it looks like this :
CREATE OR REPLACE FUNCTION gen_category_counts()
RETURNS VOID as $$
BEGIN
CREATE TEMPORARY TABLE category_stats ON COMMIT DROP AS
WITH
PC as(
SELECT category_id, COUNT(*)
FROM forum_posts fp
INNER JOIN forum_topics ft
ON ft.forum_id = fp.forum_id
AND ft.id = fp.topic_id
GROUP BY category_id
),
tc as(
SELECT category_id, COUNT(*)
FROM forum_topics
GROUP BY category_id
)
SELECT tc.category_id,tc.count AS topic_count, pc.count AS post_count
FROM tc,pc
WHERE tc.category_id = pc.category_id;
UPDATE forum_category_nodes fcn
set post_count = category_stats.post_count, topic_count = category_stats.topic_count
from category_stats
where fcn.id = category_stats.category_id;
END;
$$ LANGUAGE plpgsql;
Is there some syntactic sugar that is better than having to write out a whole sentence to declare a temp table that lives only for the duration of the function ?
Sql Server has a select into #tablename
(can't remember the exact syntax, it could be @tablename). I have seen this style of syntax used on the mailing lists, but it's syntactically incorrect, also the EBBF select into
documentation mentions temporary tables as well right next to the into clause.
So if postgres does have better sugar for implicitly defined scoped temporary tables, what is it ? :D
p.s., I'm going to be writing procedures with hundreds of lines of logic and these things add up :D
回答1:
OK, one minor shortcut:
CREATE TEMP TABLE category_stats ON COMMIT DROP AS
Other than that, for all I know, you are using the simplest form in your question - and I have been using temporary tables a lot over the last couple of years.
Honestly, I don't see why a few descriptive key words should bother me.
来源:https://stackoverflow.com/questions/11551627/postgres-implicitly-shaped-temporary-tables-syntactic-sugar-i-am-not-aware-of