Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

Why am I getting:

ERROR: syntax error at or near "'SELECT '"

In:

CREATE OR REPLACE FUNCTION GetListings (lon double precision, lat double precision, schemas name[]) 
RETURNS TABLE(
  schema VARCHAR(128),
  id BIGINT,
  product_name VARCHAR(128),
  product_type SMALLINT,
  product_subtype SMALLINT,
  product_units SMALLINT,
  product_info JSONB,
  product_image VARCHAR(256),
  is_featured BOOLEAN,
  is_special BOOLEAN,
  is_alert BOOLEAN,
  distributor_name VARCHAR(128),
  distributor_image VARCHAR(256)
) AS $$
DECLARE
  sch name;
  n text;
  t text;
BEGIN

  n := to_char(lon,'999.999999999999999');
  t := to_char(lat,'999.999999999999999');

  FOREACH sch IN ARRAY schemas 
  LOOP
    RETURN QUERY 'SELECT ''' || sch || ''', product_name, product_type, product_subtype, product_units, product_info, product_image, is_featured, is_special, is_alert, distributor_name, distributor_image FROM ' || quote_ident(sch) || '.listing WHERE ST_Contains(area, ST_SetSrid(ST_MakePoint(' || n || ', ' || t || '), 4326))';
  END LOOP;

  RETURN;

END;
$$ LANGUAGE plpgsql STRICT;
share|improve this question

closed as off-topic by Paul White, Max Vernon, RLF, Mark Storey-Smith, Phil Jan 15 at 17:41

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Too localized - this could be because your code has a typo, basic error, or is not relevant to most of our audience. Consider revising your question so that it appeals to a broader audience. As it stands, the question is unlikely to help other users (regarding typo questions, see this meta question for background)." – Paul White, RLF, Mark Storey-Smith, Phil
If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer 1

up vote 2 down vote accepted

You want RETURN QUERY EXECUTE for dynamic SQL.

With RETURN QUERY you're trying to use a string literal as the start of a query. That's nonsensical and raises a syntax error.

Also, use format with the %I and %L specifiers for identifiers and literals, instead of using concatenation. Otherwise you have SQL injection issues in your function.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.