(免责声明:Postgresql newbie。)
好的,据我所知,我的功能类似于我所看到的样品。有人能告诉我如何让我上班吗?
create or replace function get_user_by_username( username varchar(250),online boolean ) returns setof record as $$ declare result record; begin if online then update users set last_activity = current_timestamp where user_name = username; end if; return query select user_id,user_name,last_activity,created,email,approved,last_lockout,last_login,last_password_changed,password_question,comment from users where user_name = username limit 1; return; end; $$ language plpgsql;
如果要创建返回setof记录的函数,则需要在select语句中定义列类型
你的查询应该是这样的:
select * from get_user_by_username('Username',True) as f(user_id integer,user_name varchar,varchar,created date,email archar,approved boolean,last_lockout timestamp,last_login timestamp,last_password_changed timestamp,password_question varchar,comment varchar)
(您可能需要更改数据类型)
我个人喜欢类型的方法。它确保如果函数被编辑,所有的查询将返回正确的结果。这可能是一个痛苦,因为每次修改函数的参数时,您都需要重新创建/删除类型。
例如:
CREATE TYPE return_type as (user_id integer,last_activity varchar,created timestamp,email varchar,comment varchar); create or replace function get_user_by_username( username varchar(250),online boolean) returns setof return_type as $$ declare _rec return_type; begin if online then update users set last_activity = current_timestamp where user_name = username; end if; for _rec in select user_id,comment from users where user_name = username limit 1 loop return next _rec; end loop end; $$ language plpgsql;