[英]Truncate all tables in postgres database
In May 2010, Aaron and Henning both provided the code to register a function that when called later with a parameter for 'username' would truncate all the tables. 2010年5月,Aaron和Henning都提供了代码来注册一个函数,该函数稍后在使用“ username”的参数调用时将截断所有表。 It worked fine with postgres on Windows 7. Neither will work unfortunately for postgres 8.3 on Ubuntu.
在Windows 7上,它在postgres上运行良好。不幸的是,在Ubuntu上,postgres 8.3都无法使用。
An error has occurred:
ERROR: syntax error at or near "$1"
LINE 1: $1
^
QUERY: $1
CONTEXT: SQL statement in PL/PgSQL function "truncate_tables" near line 6
I have also tried simplifying the select statement to focus on the BEGIN For clause, by removing the complicated WHERE clause I used in Windows. 我还尝试通过删除我在Windows中使用的复杂WHERE子句来简化select语句,使其专注于BEGIN For子句。
Can you see the problem here? 您能在这里看到问题吗? Thanks.
谢谢。 Is it unable to pass or read the tablenames after they are retrieved?
检索表名后是否无法通过或读取表名? Doesn't a problem with $1 mean it can't find its input?
$ 1的问题不是表示找不到输入吗?
DECLARE
stmt RECORD;
statements CURSOR FOR
SELECT tablename FROM pg_tables
WHERE tablename !~* 'sql_*' and tablename !~* 'pg_*' and tablename !~* 'schema_*';
BEGIN
FOR stmt IN statements LOOP
EXECUTE 'TRUNCATE TABLE ' || quote_ident(stmt.tablename) || ' CASCADE;';
END LOOP;
END;
It appears that some of the function syntax changed between version 8.3 and 8.4. 似乎某些函数语法在版本8.3和8.4之间发生了变化。 Try this:
尝试这个:
CREATE OR REPLACE FUNCTION public.truncate_tables(username IN VARCHAR) RETURNS void AS $$
DECLARE
stmt RECORD;
BEGIN
FOR stmt IN SELECT tablename FROM pg_tables
WHERE tableowner = username AND schemaname = 'public' LOOP
execute 'TRUNCATE TABLE public.' || quote_ident(stmt.tablename) ||';';
END LOOP;
END;
$$ LANGUAGE plpgsql;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.