postgresql - 如何向 postgresql 模式中的所有表添加一列

标签 postgresql

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

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

任何帮助将不胜感激!

最佳答案

使用 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

-- or if you don't want the temporal file, use gexec to run it:
\gexec

关于postgresql - 如何向 postgresql 模式中的所有表添加一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66461941/

相关文章:

sql-server - 数据库引擎在 SQL 级别的兼容性如何?

postgresql - 如何在 Postgres 的 inet 字段上使用 LIKE

sql - Postgres : "cumulative" view of table

mysql - 为什么将 datetime 从 postgres 写入 mysql 可以工作?

java - 如何将 PostgreSQL 驱动程序 (jar) 添加到使用 liberty-maven-plugin 创建的 open-liberty microprofile fat jar?

javascript - 登录检索器上的 Sequelize 查找总是成功

sql - 在 Postgres 中查询连续列的 'run'

python - 在 PostgreSQL 中为 odoo 更新图像

python - 使用 psycopg2 从 csv 文件动态创建表

postgresql - 当我将 csv 复制到它时,postgres 如何不转义?