2016-12-27 26 views
0

我有我的數據庫中的一捆表。我需要截斷所有的表格,但不是一些。需要添加到srting postgresql select查詢結果

所以通過使用table_schema我可以得到表名單!

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

預期輸出。

truncate table table_name restart identity. 

有人告訴我有沒有更好的方法來做到這一點。

回答

3

使用format()佔位符的模式和表名,以確保該名稱是正確引用:

要正確處理表使用的外鍵,最好將cascade選項添加到truncate逗號第二:

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' 
0

可以在Postgres的concat字符串中使用||

select 'truncate table' || table_name::text || ' restart identity' 
from information_schema.tables 
where table_schema = 'public 

看看9.4. String Functions and Operators