简体   繁体   中英

I am getting the error subquery must return only one column when I try to run the following query:

CREATE or REPLACE PROCEDURE checkUpdateAdd(imei1 inout text, assetName1 inout text)
language 'plpgsql'
AS $BODY$
declare
begin
    PERFORM * from msdata;
if (select * from msdata where imei = imei1) then
    --UPDATE "public"."msdata"
    UPDATE public.msdata SET assetname1 = assetname where imei = imei1;
    -- return assetname;
-- SELECT * FROM msdata ORDER BY imei ASC;
elseif (select * from msdata where imei != imei1) then
    Insert into public.msdata(imei,assetname) values (imei1,assetname1);
    --return;
end if;
    -- return (null,null);
end;
$BODY$;

call checkUpdateAdd('123','abc1');
SELECT * FROM msdata; 

where msdata is an existing table with coloumns imei and assetname so now if I have to create a procedure which on calling - creates or updates the msdata

I would rather create a function that updates or inserts and returns the old value of assetname field upon update or null (as there is no old value) upon insert. Please note the FOUND predefined variable.

CREATE or REPLACE FUNCTION checkUpdateAdd(imei1 text, assetName1 text)
returns text language 'plpgsql' AS
$BODY$
declare
  retval text;
begin
  select assetname into retval from msdata where imei = imei1;
  if FOUND then -- (imei = imei1) exists, return the old assetname value
    update msdata SET assetname = assetname1 where imei = imei1;
    return retval;
  else
    insert into msdata(imei, assetname) values (imei1, assetname1);
    return null;
  end if;
end;
$BODY$;

Btw. if imei is a primary key or if it has an unique constraint then the task becomes much more simple. You ca use insert on conflict do update and do not need a function or procedure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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