首页 > 解决方案 > 如何将一列添加到 postgresql 模式中的所有表

问题描述

问题很简单,但似乎无法在任何地方找到具体答案。

我需要更新我的 postgresql 架构中的所有表,以包含一个带有默认 NOW() 的时间戳列。我想知道如何通过查询来做到这一点,而不必去每个单独的表。架构中有数百个表,它们都只需要添加一个带有默认值的列。

任何帮助将不胜感激!

标签: postgresql

解决方案


使用 psql 的简单方法,运行查询以生成命令,保存并运行结果

-- Turn off headers:
\t
-- Use SQL to build SQL:
SELECT 'ALTER TABLE public.' || table_name || ' add fecha timestamp not null default now();'
FROM information_schema.tables
WHERE table_type = 'BASE TABLE' AND table_schema='public';
-- If the output looks good, write it to a file and run it:
\g out.tmp
\i out.tmp

推荐阅读