Reputation: 3
I am debugging a sql file in PostgreSQL's pgAdminIII, and this statement creates a syntax error when executing:
ERROR: syntax error at or near "v"
LINE 81384: ...n.oid = c.relnamespace WHERE c.relkind IN (\'v\') AND n...
The statement:
CREATE OR REPLACE FUNCTION getnextview() RETURNS name AS ' DECLARE my_record RECORD; viewName name; BEGIN FOR my_record IN SELECT c.relname FROM pg_catalog.pg_class AS c LEFT JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace WHERE c.relkind IN (\'v\') AND n.nspname NOT IN (\'pg_catalog\', \'pg_toast\') AND pg_catalog.pg_table_is_visible(c.oid) LIMIT 1 LOOP viewName := my_record.relname; END LOOP; RETURN (viewName); END; ' LANGUAGE 'plpgsql' VOLATILE;
Note, the pg_catalog and pg_toast also error.
Upvotes: 0
Views: 2269
Reputation: 658562
This does the same exactly, just simpler:
CREATE OR REPLACE FUNCTION getnextview()
RETURNS name AS
$BODY$
SELECT c.relname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'v'
AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
AND pg_catalog.pg_table_is_visible(c.oid)
LIMIT 1
$BODY$
LANGUAGE sql STABLE;
Upvotes: 1
Reputation:
So the full statement does change the picture substantially.
Your problem is the nesting of single quotes. If you use PostgreSQL's "dollar quoting" everything is a lot easier:
CREATE OR REPLACE FUNCTION getnextview()
RETURNS name
AS
$body$
DECLARE
my_record RECORD;
viewName name;
BEGIN
FOR my_record IN
SELECT c.relname
FROM pg_catalog.pg_class AS c
LEFT JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace
WHERE c.relkind IN ('v')
AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
AND pg_catalog.pg_table_is_visible(c.oid)
LIMIT 1
LOOP
viewName := my_record.relname;
END LOOP;
RETURN (viewName);
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE;
Upvotes: 2