我正在尝试创建满足以下条件的查询:
给定用户名和电子邮件地址,
user_id
新用户,如果已经使用了用户名则返回-1,如果已经采用电子邮件地址则返回-2,如果两者都被采用则返回-3(或任何其他确定错误原因的方法到目前为止,我有以下功能:
CREATE OR REPLACE FUNCTION add_user
(character varying(40), character varying(255), character(60))
RETURNS integer
AS $body$
DECLARE
id record;
BEGIN
IF EXISTS(SELECT 0 FROM user_account WHERE username = $1 AND email_address = $2)
THEN RETURN 3;
ELSEIF EXISTS(SELECT 0 FROM user_account WHERE username = $1)
THEN RETURN 1;
ELSEIF EXISTS(SELECT 0 FROM user_account WHERE email_address = $2)
THEN RETURN 2;
ELSE FOR id IN INSERT INTO user_account (username, email_address, hash) values ($1, $2, $3) RETURNING user_id
LOOP
RETURN id;
END LOOP;
END IF;
RETURN 0;
END;
$body$
LANGUAGE plpgsql
VOLATILE
是否有一种更优雅的方式来实现这一点,而不会遇到声明记录和循环的麻烦?
答案 0 :(得分:3)
您不需要循环只将declare
id integer; -- use an integer variable
begin
...
ELSE
INSERT INTO user_account (username, email_address, hash) values ($1, $2, $3)
RETURNING user_id
INTO id; --<< here
return id;
END IF;
end;
的结果存储到您的变量中;
linDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker"); }
});