简体   繁体   中英

update in a function sql in dbeaver/postgres

I have to update a field in a table with concat() and I'm thinking to use a function with an update sql. I also want to have a rollback if update doesnt' work.

I have this function but it just works the select sql and for the first row of the table "clients"

CREATE OR REPLACE FUNCTION value_concat()
     RETURNS record
     LANGUAGE plpgsql
    AS $function$
        DECLARE
            rows_affected integer := 0;
            query constant text not null := 'select * from db.clients';     
            result record;
                
    BEGIN           
        EXECUTE query INTO result;
        RETURN result;

        UPDATE db.clients SET clients.name = concat(clients.name, '-US');           

        exception when raise_exception
           then
               begin
                   rows_affected := 0;
                   rollback;
               end;
      RETURN record;
    END;
$function$
;

Do I have to make a select sql before the update?

Why the update is not working, should I do a for/loop before the update sql?

The below code returns just one record and not all records form the select sql, why?

  EXECUTE query INTO result;
  RETURN result;

I hope this help.

CREATE OR REPLACE FUNCTION value_concat()
     RETURNS TABLE (
        field_name1 VARCHAR,
        field_name2 INT [, ...]
       )
     LANGUAGE plpgsql
    AS $function$
        
BEGIN           
 

    UPDATE db.clients SET clients.name = concat(clients.name, '-US');           
    
    RETURN QUERY
         select * from db.clients;

    exception when raise_exception
       then
           begin
               rows_affected := 0;
               rollback;
           end;
  RETURN record;
END;
$function$
;

Do I have to make a select SQL before the update?

There's no need to select, it works well. You should check the query to apply where for unwanted updates for other records.

Why the update is not working, should I do a for/loop before the update SQL?

Because you're returning before the update and the rest of the code is always skipped.

The below code returns just one record and not all records form the select sql, why?

It's because you just return a record type. the record type can only store one row from a result.

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