The problem seems to be misusing the backslash, but anyway putting this query into a text variable shouldn't be needed in the first place.
What about this form:
FOR result IN SELECT * FROM categories WHERE cat_tree ~ '*.'|| s_cat::text || '.*'
LOOP
RETURN NEXT result;
END LOOP;
And if the LOOP just has to return the results, you may just as well avoid it and return the query directly:
RETURN QUERY SELECT * FROM categories WHERE cat_tree ~ '*.'|| s_cat::text || '.*';
EDIT:
Since the operator is ltree ~ lquery
and ~
binds tighter than ||
, the right operand should be parenthesized and cast to lquery
:
RETURN QUERY SELECT * FROM categories
WHERE cat_tree ~ ('*.'|| s_cat::text || '.*')::lquery;