问题描述
我想在保持序列标识的同时截断整个数据库。我想出了这样的事情:
WITH tables_to_be_truncated AS (
SELECT table_name
FROM information_schema.tables
WHERE table_type='BASE TABLE'
AND table_schema='public'
AND table_name NOT IN ('admins','admin_roles')
)
TruncATE TABLE (SELECT table_name FROM tables_to_be_truncated) CONTINUE IDENTITY RESTRICT;
我收到此错误:
ERROR: Syntax error at or near "TruncATE"
LINE 9: TruncATE TABLE (SELECT table_name FROM tables_to_be_truncated...
我确实有截断表的权限,当我运行像 TruncATE TABLE access_tokens
这样的单个表时,它工作正常。
我也试过这个
TruncATE TABLE (SELECT string_agg(table_name,',') FROM tables_to_be_truncated) CONTINUE IDENTITY RESTRICT
效果不佳。
从我在其他帖子中看到的情况来看,人们正在使用函数来做这件事。老实说,我不想走这条路,但如果这是唯一的方法......
解决方法
你不需要一个函数。 anonymous code block
可以:
DO $$
DECLARE row RECORD;
BEGIN
FOR row IN SELECT table_name
FROM information_schema.tables
WHERE table_type='BASE TABLE'
AND table_schema='public'
AND table_name NOT IN ('admins','admin_roles')
LOOP
EXECUTE format('TRUNCATE TABLE %I CONTINUE IDENTITY RESTRICT;',row.table_name);
END LOOP;
END;
$$;
除此之外,我认为您无法使用纯 SQL 运行动态查询。
演示:db<>fiddle