简体   繁体   English

如何在 PL/pgSQL 中返回登录 function 中的数据? 我想返回 email 和密码匹配的表。 Email 是独一无二的

[英]How to return data in login function in PL/pgSQL? I want to return table where email and password matches. Email is unique

The function doesn't throw any error nor does it show any return value. function 不会抛出任何错误,也不会显示任何返回值。

CREATE OR REPLACE FUNCTION login(iemail VARCHAR,ipassword VARCHAR)
RETURNS TABLE(id INTEGER, name VARCHAR, lastName VARCHAR, age INTEGER, mobile VARCHAR,email VARCHAR)
LANGUAGE 'plpgsql'
AS $$
#variable_conflict use_variable
BEGIN
RETURN QUERY SELECT id, name, lastName, age, mobile,email from usertable WHERE email = iemail AND password = ipassword;
END;
$$;

Below query gives me a return value.下面的查询给了我一个返回值。 So, I know my query statement is right.所以,我知道我的查询语句是正确的。 Also, return type of variables are also checked.此外,还检查变量的返回类型。

SELECT id, name, lastName, age, mobile,email from usertable 
WHERE email='jaysrdra@gmail.com' AND password ='passwords';

i am calling the function with:我正在拨打 function:

SELECT * FROM login('jaysrdra@gmail.com','passwords');

The #variable_conflict use_variable is the reason. #variable_conflict use_variable是原因。 As all your output variables (=columns) have the same name as the table columns, Postgres returns the output "variables" which are not initialized.由于所有 output 变量(=列)与表列同名,Postgres 返回 output 未初始化的“变量”。

Use an explicit table reference inside the function's query to avoid the name clash:在函数查询中使用显式表引用以避免名称冲突:

CREATE OR REPLACE FUNCTION login(iemail VARCHAR,ipassword VARCHAR)
RETURNS TABLE(id INTEGER, name VARCHAR, lastName VARCHAR, age INTEGER, mobile VARCHAR, email VARCHAR)
LANGUAGE plpgsql
AS $$
BEGIN
  RETURN QUERY 
    SELECT u.id, u.name, u.lastname, u.age, u.mobile, u.email 
    from usertable u
    WHERE u.email = iemail 
    AND u.password = ipassword;
END;
$$;

Note that for encapsulating a simple query into a function a language sql function is typically the better choice - it also avoids the clash between variables and column names:请注意,为了将简单查询封装到 function 中, language sql function 通常是更好的选择 - 它还避免了变量和列名之间的冲突:

CREATE OR REPLACE FUNCTION login(iemail VARCHAR,ipassword VARCHAR)
  RETURNS TABLE(id INTEGER, name VARCHAR, lastName VARCHAR, age INTEGER, mobile VARCHAR, email VARCHAR)
LANGUAGE sql
AS $$
  SELECT id, name, lastname, age, mobile, email 
  from usertable 
  WHERE email = iemail 
  AND password = ipassword;
$$;

Looks more like you are not calling the function correctly, should be something like this to call it.看起来更像是您没有正确调用 function,应该这样调用它。

SELECT * INTO some_variable FROM login('jaysrdra@gmail.com', 'passwords');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM