[英]Using update inside of PL/pgSQL
To begin with, I am a newbie to SQL and PostgreSQL. It might be a silly beginner's mistake.首先,我是 SQL 和 PostgreSQL 的新手。这可能是一个愚蠢的初学者错误。
create or replace function temporary_function_for_getting(admission_number_text text,organization_id bigint,user_object_json json)
returns table(admission_number text ,status text)
LANGUAGE plpgsql
AS $function$
declare
select_user_with_id text :=
'select $1 as admin,
case
when $2 is null then ''Invalid organization ID''
when $1 is null then ''Invalid admission number''
when exists (update hsg_id_master set hsg_suffix=''something new'' where admission_number=$1 and organization_id=$2 returning hsg_suffix )
then ''success''
else ''User does not exists.''
end;';
begin
return query
execute select_user_with_id using admission_number_text,organization_id;
end;
$function$ ;
^This isn't working provides me with an error ^这不起作用给我提供了一个错误
SQL Error [42601]: ERROR: syntax error at or near "update" SQL 错误 [42601]:错误:“更新”处或附近的语法错误
Where: PL/pgSQL function temporary_function_for_getting(text,bigint,json) line 13 at RETURN QUERY.其中:PL/pgSQL function temporary_function_for_getting(text,bigint,json) 第 13 行,返回查询。
The update query works fine by itself not sure what i am doing wrong.更新查询本身工作正常,不确定我做错了什么。 Would appreciate if anyone could point me to the resource and/or a better way of doing the same process.如果有人能指出资源和/或执行相同过程的更好方法,我将不胜感激。
You seem to want an update CTE for the base query.您似乎需要基本查询的更新 CTE。 Try something like this:尝试这样的事情:
with u as (
update hsg_id_master
set hsg_suffix = ''something new''
where admission_number = $1 and organization_id = $2
returning hsg_suffix
)
select $1 as admin,
(case when $2 is null then ''Invalid organization ID''
when $1 is null then ''Invalid admission number''
when exists (select 1 from u)
then ''success''
else ''User does not exists.''
end);
Note that the update
will not update any rows if either $1
or $2
is NULL
, because the where
clause will evaluate to NULL
-- filtering out all rows.请注意,如果$1
或$2
为NULL
,则update
不会更新任何行,因为where
子句的计算结果为NULL
—— 过滤掉所有行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.