【发布时间】:2018-05-19 20:43:12
【问题描述】:
我的数据库中有大约 700 个表。当我运行下面的脚本时,大约需要 1 小时。如何优化此查询?
数据库:Postgres
DO $$
DECLARE
tables_list CURSOR FOR
select distinct t_name, t_schema from information_schema.columns
where column_name = 'deleted_flag'
and t_schema='customer' and t_name not like 'v_%';
BEGIN
FOR t_record IN tables_list LOOP
EXECUTE 'update ' || t_record.table_schema || '.' || t_record.table_name || ' set deleted_flag=false';
END LOOP;
end;
$$;
最后,此架构中的所有表都应将此字段 deleted_flag 设置为 false。我必须在生产环境中经常运行这个脚本。如果有人可以帮助如何优化此脚本,不胜感激。
你认为如果在where子句中添加一个检查,
EXECUTE 'update ' || t_record.table_schema || '.' || t_record.table_name || ' set deleted_flag=false where deleted_flag=true';
执行时间会更短吗?
【问题讨论】:
-
强烈建议不要使用字符串连接。改用
FORMAT()函数(它处理混合大小写和标识符中嵌入的空白) -
你有例子吗?它适用于 postgres 吗?
标签: sql postgresql