[英]PostgreSQL: CREATE FUNCTION returns one row by primary key
I wrote the following function:我写了以下函数:
-- Authenticate: Get session_id with user_id
CREATE OR REPLACE FUNCTION sessions_get(bigint) RETURNS SETOF char(32) AS
$$
SELECT strip_hyphens(id) as id FROM sessions WHERE user_id = $1;
$$
LANGUAGE SQL;
I want to be able to run the query SELECT sessions_get(1)
to get the session ID with user ID 1. And, I want the name of the column returned to be id
.我希望能够运行查询
SELECT sessions_get(1)
以获取用户 ID 为 1 的会话 ID。而且,我希望返回的列名称为id
。
Is that possible?那可能吗? Or, would the query have to be
SELECT * FROM sessions_get(1)
?或者,查询必须是
SELECT * FROM sessions_get(1)
吗? In that case, it'd be shorter to just write SELECT sessions_get(1) as id
.在这种情况下,将
SELECT sessions_get(1) as id
写SELECT sessions_get(1) as id
会更短。 Which is better?哪个更好?
Can I remove SETOF
since I know this function will always return 0 or 1 rows?我可以删除
SETOF
因为我知道这个函数总是返回 0 或 1 行吗? I know this because user_id
is the primary key of the sessions
table.我知道这是因为
user_id
是sessions
表的主键。
Change the function to:将函数更改为:
-- Authenticate: Get session_id with user_id CREATE FUNCTION sessions_get(bigint, OUT id char(32)) RETURNS SETOF char(32) AS $$ SELECT strip_hyphens(id) FROM sessions WHERE user_id = $1; $$ LANGUAGE SQL;
Then, use the query: SELECT * FROM sessions_get(1)
.然后,使用查询:
SELECT * FROM sessions_get(1)
。
Use SETOF
so that 0 rows are returned when none exist.使用
SETOF
以便在不存在时返回 0 行。 Otherwise, you'll get 1 empty row.否则,您将获得 1 个空行。
To avoid returning SETOF you can always do this:为避免返回 SETOF,您始终可以这样做:
CREATE OR REPLACE FUNCTION sessions_get(IN a bigint, OUT id char(32)) RETURNS char(32) AS
$$
SELECT strip_hyphens(id) INTO id FROM sessions WHERE user_id = $1;
RETURN;
$$
LANGUAGE SQL;
Hope it helps.希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.