I have the following script that I want output to the screen from.
CREATE OR REPLACE FUNCTION randomnametest() RETURNS integer AS $$
DECLARE
rec RECORD;
BEGIN
FOR rec IN SELECT * FROM my_table LOOP
SELECT levenshtein('mystring',lower('rec.Name')) ORDER BY levenshtein;
END LOOP;
RETURN 1;
END;
$$ LANGUAGE plpgsql;
I want to get the output of the levenshein() function in a table along with the rec.Name. How would I do that? Also, it is giving me an error about the line where I call levenshtein(), saying that I should use perform instead.
If you want the output from a PL/pgSQL function like the title says:
CREATE OR REPLACE FUNCTION randomnametest(_mystring text)
RETURNS TABLE (l_dist int, name text)
LANGUAGE plpgsql AS
$func$
BEGIN
RETURN QUERY
SELECT levenshtein(_mystring, lower(t.name)), t.name
FROM my_table t
ORDER BY 1;
END
$func$;
RETURNS TABLE
.RETURN QUERY
to return records from the function.OUT
parameters (from the RETURNS TABLE
clause) by table-qualifying column names in queries. OUT
parameters are visible everywhere in the function body.There are other ways, but this is simplest for the task - while you can't simplify to a plain SQL function.
For one-time use, consider the nested query without any function wrapper.