对于任何不返回行的SQL命令,例如没有
RETURNING
子句的INSERT
命令,您可以通过编写该命令在PL/pgSQL函数内部执行该命令。出现在命令文本中的任何PL/pgSQL变量名称都被视为参数,然后在运行时提供变量的当前值作为参数值。
但是当我在我的查询中使用变量名时,会出现错误:
ERROR: syntax error at or near "email" LINE 16: ...d,email,password) values(identity_id,current_ts,''email'',''...
这是我的函数:
CREATE OR REPLACE FUNCTION app.create_identity(email varchar,passwd varchar)
RETURNS integer as $$
DECLARE
current_ts integer;
new_identity_id integer;
int_max integer;
int_min integer;
BEGIN
SELECT extract(epoch FROM now())::integer INTO current_ts;
int_min:=-2147483648;
int_max:= 2147483647;
LOOP
BEGIN
SELECT floor(int_min + (int_max - int_min + 1) * random()) INTO new_identity_id;
IF new_identity_id != 0 THEN
INSERT into app.identity(identity_id,date_inserted,email,password) values(identity_id,current_ts,''email'',''passwd'');
RETURN new_identity_id;
END IF;
EXCEPTION
WHEN unique_violation THEN
END;
END LOOP;
END;
$$ LANGUAGE plpgsql;
为什么我在查询中使用变量时,Postgres会抛出错误?应该如何编写呢?
email
的值。 - Nulikp_email
,你不应该将其写成'p_email'
。这不是关于美元引用和转义的问题,而只是对变量解释的基本误解。 - IMSoP