postgresql数据库支持数据库分表,但是有时会遇到,现场的数据库已经在跑了,但是新的需求,需要增加一个字段,
字段增加,分表会自动增加的,但是规则不会实时更新,规则不更新的话,分表新的字段的值就不会更新掉。
其实只需要把所有的规则修改下就可以了,但是有时规则比较多,手动修改还是有点麻烦,所以,就写了一个函数来
做这个功能,这个使用起来还是很快很方便的,这里使用到的就是游标、函数
-------------该函数只需要主表名称和时间字段,即可针对主表字段有增加、修改、删除的情况时,一键修改规则------------------------------
----------------------------定制项目有时会遇到有分表需要增加字段的情况,但是现场不会重新安装,但是----------------------------------------------------------------
create
or replace function cursor_demo (
tabname character varying,
timefield character varying
) returns refcursor as $body$ declare
sub_tab_name varchar (1000) ; column_name_desc varchar (1000) ; declare
fetch_sub_tab_refcursor cursor for select
tablename
from
pg_tables
where
tablename like tabname || '_%' ; declare
fetch_sub_column_refcursor cursor for select
column_name
from
information_schema. columns
where
table_name = tabname ; declare
sql_desc varchar (1000) ; declare
value_desc varchar (1000) ; declare
all_sql_desc varchar (2000) ; declare
st_time varchar (100) ;
begin
open fetch_sub_tab_refcursor ; loop fetch fetch_sub_tab_refcursor into sub_tab_name ;
if found then
if (
length (tabname) = (length(sub_tab_name) - 7)
) then
if (
tabname = (
substring (
sub_tab_name
from
1 for length (tabname)
)
)
) then
st_time := substring (
sub_tab_name
from
length (tabname) + 2 for length (sub_tab_name)
) ; st_time := substring (st_time from 1 for 4) || '-' || substring (st_time from 5 for 6) ; sql_desc := 'create or replace rule insert_' || sub_tab_name || ' as on insert to ' || tabname || ' where new.' || timefield || ' >= ''' || substring (
to_char(
to_timestamp(st_time, 'yyyy-mm-dd'),
'yyyy-mm-dd'
)
from
1 for 10
) || '''::date and new.' || timefield || ' <''' || substring (
to_char(
to_timestamp(st_time, 'yyyy-mm-dd') + interval '1 month',
'yyyy-mm-dd'
)
from
1 for 10
) || '''::date do instead insert into ' || sub_tab_name || '(' ; value_desc := 'values (' ; open fetch_sub_column_refcursor ; loop fetch fetch_sub_column_refcursor into column_name_desc ;
if found then
sql_desc := sql_desc || column_name_desc || ',' ; value_desc := value_desc || 'new.' || column_name_desc || ',' ;
else
exit ;
end
if ;
end loop ; sql_desc := substring (
sql_desc
from
1 for length (sql_desc) - 1
) || ')' ; value_desc := substring (
value_desc
from
1 for length (value_desc) - 1
) || ');' ; all_sql_desc := sql_desc || value_desc ; execute all_sql_desc ; close fetch_sub_column_refcursor ;
else
end
if ;
else
end
if ;
else
exit ;
end
if ;
end loop ; close fetch_sub_tab_refcursor ; return fetch_sub_tab_refcursor ; exception
when others then
raise exception 'error--(%)',
sqlerrm ;
end ; $body$ language plpgsql;
--------调用方式----有两个参数,第一个是主表名,第二个是根据哪个字段进行分表------
begin
;
select
cursor_demo (
'your_table_name',
'your_field'
);
commit;