好吧,我正在尝试创建一个简单的过程,检查用户是否具有此类登录,如果没有 - 在users表中添加新行。但是遇到了意想不到的问题。
CREATE OR REPLACE FUNCTION register_user(character varying, character varying, character varying,character varying,character varying)
RETURNS bigint AS
$BODY$
DECLARE
new_user_login ALIAS FOR $1;
new_user_password ALIAS FOR $2;
new_user_email ALIAS FOR $3;
new_user_first_name ALIAS FOR $4;
new_user_last_name ALIAS FOR $5;
login_exist bigint;
new_user_id bigint;
emails_array character varying array; --yep, it's array of emails
BEGIN
SELECT INTO login_exist count(login) FROM users WHERE users.login = new_user_login;
IF (login_exist = 0) THEN
SELECT array_append(emails_array, new_user_email);
INSERT INTO users (login,password,emails,first_name,last_name)
VALUES (new_user_login,new_user_password,emails_array,new_user_first_name,new_user_last_name)
RETURNING id INTO new_user_id;
RETURN new_user_id;
ELSE
RETURN 0;
END IF;
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
它在SELECT INTO上返回sql-state:42601。但是如果只有count是0.当登录存在时它正确返回0; 问题是什么?我甚至不知道这是什么。 请求帮助;
答案 0 :(得分:1)
这条指令:
SELECT array_append(emails_array, new_user_email);
应该失败,因为array_append
返回修改后的数组并且不允许忽略select的结果。
如果你想追加到源数组中,那应该是:
SELECT array_append(emails_array, new_user_email) INTO emails_array;
然而,这甚至不是必要的。您可以将函数体简化为:
BEGIN
INSERT INTO users (login,password,emails,first_name,last_name)
SELECT new_user_login,new_user_password,array[new_user_email],new_user_first_name,new_user_last_name
WHERE NOT EXISTS (select 1 FROM users WHERE users.login = new_user_login)
RETURNING id INTO new_user_id;
RETURN coalesce(new_user_id,0);
END;
答案 1 :(得分:1)
除了@Daniel already answered之外,不要使用过时的ALIAS
来命名函数参数。 Quoting the manual here:
最好只将其用于覆盖预定名称。
改为使用argument names:
CREATE OR REPLACE FUNCTION register_user(_login text
, _password text
, _email text
, _first_name text
, _last_name text)
RETURNS bigint AS
$func$
DECLARE
_id bigint;
BEGIN
INSERT INTO users (login, password, emails, first_name, last_name)
SELECT _login, _password, ARRAY[_email], _first_name, _last_name
WHERE NOT EXISTS (SELECT 1 FROM users WHERE login = _login)
RETURNING id INTO _id;
RETURN COALESCE(_id, 0);
END
$func$ LANGUAGE plpgsql;