Reputation: 31
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. It worked fine with postgres on Windows 7. Neither will work unfortunately for postgres 8.3 on Ubuntu.
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.
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?
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;
Upvotes: 3
Views: 5529
Reputation: 3790
It appears that some of the function syntax changed between version 8.3 and 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) ||' CASCADE;';
END LOOP;
END;
$$ LANGUAGE plpgsql;
Upvotes: 3