Answer the question
In order to leave comments, you need to log in
How to save a select to a variable?
Peace for everyone!
And the question is immediately this:
In the function code example, you can see two `SELECT ... AS _query` and of course you can’t do that; Help to correctly convert the `_query` function argument for further work with it in the query;
SQL is completely zero and I touch it only when absolutely necessary, I tried to declare variables through `DECLARE` but the interpreter (if I may say so) of the
postgresql DBMS is constantly swearing at something.
Thank you very much in advance!)
CREATE OR REPLACE FUNCTION public.search_movies(_query character varying)
RETURNS TABLE(id bigint, _table character varying, nameru character varying, nameen character varying, image text)
LANGUAGE sql
AS $function$
SELECT regexp_replace(_query, '\M', ':* ', 'gi') AS _query;
SELECT regexp_replace(_query, '\M\:\*(?=(\s+?|)\m)', ':* | ', 'gi') AS _query;
SELECT *
FROM (
(
SELECT
id,
'movie' AS _table,
nameru,
nameen,
CAST(posters AS TEXT) AS image
FROM movies
WHERE tsv @@ to_tsquery('ru', _query)
LIMIT 10
)
UNION
(
SELECT
id,
'staff' AS _table,
staff_name,
staff_name_en,
CAST(staff_photo AS TEXT) AS image
FROM movie_staff
WHERE tsv @@ to_tsquery('ru', _query)
LIMIT 10
)
) t
ORDER BY
CASE
WHEN _table = 'movie'
THEN 1
WHEN _table = 'staff'
THEN 2
ELSE 3
END;
$function$
Answer the question
In order to leave comments, you need to log in
Zero in SQL, but take up stored procedures? Boldly!
You have problems with declaring variables in the declare block because you should use language plpgsql instead of language sql. And after declaring a variable, you can do
SELECT regexp_replace(_query, '\M', ':* ', 'gi') INTO some_var;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question