postgres 9.0.13 update values from (select values from)

55 Views Asked by At

based on the docs https://www.postgresql.org/docs/9.1/static/sql-update.html It's not possible what I am trying to do (at the very bottom of that page)

================

UPDATE accounts SET (contact_last_name, contact_first_name) =
    (SELECT last_name, first_name FROM salesmen
     WHERE salesmen.id = accounts.sales_id);

================

Is there an alternative way to do this?

    db=> update "Template" set ("MsgCategoryName","FromAddress","FromName","ToAddress","ToName","BccAddress","EmailSubject","EmailHTML","EmailPlanText") = (Select "MsgCategoryName","FromAddress","FromName","ToAddress","ToName","BccAddress","EmailSubject","EmailHTML","EmailPlanText" from "Template" where "AccountID" = 1016020479 and "LocaleID" = 'nl' and "TmplName" = 'Invoice/Nobrand/PDF') where "AccountID" = 1017069459 and "TmplName" = 'Invoice/Nobrand/PDF' and "LocaleID" = 'nl';
ERROR:  syntax error at or near "Select"
LINE 1: ...s","EmailSubject","EmailHTML","EmailPlanText") = (Select "Ms...

db=> select version();
                                                      version                                                      
-------------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.0.13 on x86_64-unknown-linux-gnu, compiled by GCC gcc (GCC) 4.4.6 20110731 (Red Hat 4.4.6-3), 64-bit
(1 row)
                                                         ^
1

There are 1 best solutions below

0
Vao Tsun On

I don't have this old version to check, but I believe that you can't use CTE for update (what you can for sure with 9.1), in this case you can plpgsql it:

do
$$
declare _r record;
begin
  for _r in (SELECT id,last_name, first_name FROM salesmen JOIN accounts on salesmen.id = accounts.sales_id) loop
    UPDATE accounts SET contact_last_name = _r.last_name, contact_first_name = _r.first_name where sales_id = _r.id;
  end loop;
end;
$$
;