iT邦幫忙

0

postgresql 動態SQL加入if判斷

  • 分享至 

  • xImage

因為公司Table有用partition按月切開,
所以想寫一個函數可以動態來讀資料,
大概是下面那樣,


CREATE OR REPLACE FUNCTION dynamic_push("month_yyyymm" text)
RETURNS TABLE(m_id text, m_date timestamp, is_read text) AS
$$
BEGIN
execute
'
select *
from
(
select m_id::text, m_date::timestamp senddate, is_read::text
from admin.push_'||month_yyyymm||'
where m_date between now()-8 and date(now())-1
)
union
(
select *
from
(
select m_id::text, m_date::timestamp senddate, is_read::text
from admin.push_'||(month_yyyymm::numeric-1)::text||'
where m_date between now()-8 and date(now())-1
)
)
';
END;
$$ LANGUAGE plpgsql;

select *
from dynamic_apppush(to_char(now(),'yyyymm')::text);


但想加判斷式進去,判斷同月即執行第一段,跨月再執行整串,
修改後如下,但是執行一直有Error,想求助大神問題大概出在哪呢?
(Error 一直發生在 ; 處)


CREATE OR REPLACE FUNCTION dynamic_push("month_yyyymm" text)
RETURNS TABLE(m_id text, m_date timestamp, is_read text) AS
$$
BEGIN
if to_char(now()-8,'yyyymm') = to_char(date(now())-1,'yyyymm') then
execute
'
select *
from
(
select m_id::text, m_date::timestamp senddate, is_read::text
from admin.push_'||month_yyyymm||'
where m_date between now()-8 and date(now())-1
)
';
else
execute
'
select *
from
(
select m_id::text, m_date::timestamp senddate, is_read::text
from admin.push_'||month_yyyymm||'
where m_date between now()-8 and date(now())-1
)
union
(
select *
from
(
select m_id::text, m_date::timestamp senddate, is_read::text
from admin.push_'||(month_yyyymm::numeric-1)::text||'
where m_date between now()-8 and date(now())-1
)
)
';
END IF;
END;
$$ LANGUAGE plpgsql;


ty201457 iT邦新手 5 級 ‧ 2020-03-11 19:55:37 檢舉
不好意思,找到問題了!!!感謝大家~
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
不明
【**此則訊息已被站方移除**】

尚未有邦友回答

立即登入回答