gpt4 book ai didi

sql - 需要在postgresql select查询结果中添加到string

转载 作者:行者123 更新时间:2023-11-29 14:18:00 26 4
gpt4 key购买 nike

我的数据库中有一堆表。我需要截断所有表而不是部分表。

所以通过使用 table_schema 我可以获得表名列表!

select  ''as "truncate", table_name 
from information_schema.tables
where table_schema = 'public'

预期输出。

truncate table table_name restart identity.

有人告诉我有没有更好的方法来做到这一点。

最佳答案

format() 与架构和表名的占位符一起使用,以确保名称被正确引用:

要正确处理表使用的外键,最好在 truncate 命令中添加 cascade 选项:

select format('truncate table %I.%I restart identity cascade;', table_schema, table_name) as stmt
from information_schema.tables
where table_schema = 'public';

另一种选择是在一条语句中截断所有表:

select concat('truncate table ', string_agg(format('%I.%I', table_schema, table_name), ', '), ' restart identity;') as stmt
from information_schema.tables
where table_schema = 'public'

关于sql - 需要在postgresql select查询结果中添加到string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41344084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com