Answer the question
In order to leave comments, you need to log in
What is the correct way to use arguments in a function?
I want to create a function that will accept a username and role as input
CREATE OR REPLACE FUNCTION create_user(user_name varchar, role_name varchar)
RETURNS SETOF varchar AS
$BODY$
BEGIN
CREATE USER user_name PASSWORD (SELECT random_string((SELECT random_int_between(5,15))));
GRANT role_name TO user_name;
RETURN QUERY SELECT * FROM all_users;
END;
$BODY$ LANGUAGE plpgsql;
Answer the question
In order to leave comments, you need to log in
CREATE USER user_name PASSWORD (SELECT random_string((SELECT random_int_between(5,15))));
Non-optimizable SQL commands (also called utility commands) are not capable of accepting query parameters. So automatic substitution of PL/pgSQL variables does not work in such commands. To include non-constant text in a utility command executed from PL/pgSQL, you must build the utility command as a string and then EXECUTE it, as discussed in Section 43.5.4.
SELECT random_string(SELECT random_int_between(5,15)) INTO pass;
EXECUTE format('CREATE USER %I PASSWORD %L', user_name, pass);
EXECUTE format('GRANT %I TO %I', role_name, user_name);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question