我有两个桌子。
表A
-------------------------------------------
id | date | shiftId | activityId |
-------------------------------------------
1 2018-09-09 1 100
2 2018-09-09 1 101
表B
------------------------------------------------------------------
id | reading | resourceId |date | shiftId | activityId
------------------------------------------------------------------
1 10.0 10 2018-09-09 1
2 11.0 11 2018-09-09 1
现在,我想从表A更新表B activityId,并在 shiftid 和 shiftDate 上查询表A。
如何编写存储过程以循环更新表B?
我在下面的查询中尝试过
create or replace FUNCTION Update_TableB_ActivityId()
Returns Void as $$
Declare
rec RECORD;
query text;
activityId integer;
BEGIN
query := 'select * from TableB where "activityId" is null;
FOR rec IN execute query
LOOP
execute 'select "activityId" from TableB where "date"=rec."date"' into activityId;
execute 'Update TableB set "activityId"=activityId where "id"=rec."id"';
END LOOP;
END;
$$ LANGUAGE plpgsql;
答案 0 :(得分:0)
使用带有连接的更新,因此不需要循环存储过程
对于mysql:
UPDATE tableb
JOIN tablea on tablea.shiftid=tableb.shiftid and
tablea.date=tableb.date
SET tableb.activityid=tablea.activityid
对于postgres:
UPDATE tableB
SET tableb.activityid=tablea.activityid
FROM tableA
WHERE tableA.shiftid=tableB.shiftid and
tableA.date=tableB.date;
答案 1 :(得分:0)
This is POSTGRESQL STORED PROCEDURE
CREATE OR REPLACE FUNCTION schemaName.updateactivityid()
RETURNS text AS
$BODY$
declare
c_shiftId int;
c_activityId int;
c_date date;
_curs cursor FOR select distinct shiftId,activityId,date from schemaName.TableA; ----Cursor
BEGIN
OPEN _curs ; --- Opening Cursor
LOOP
FETCH _curs INTO c_shiftId,c_activityId,c_date;
--- Fetching Cursor Data into Variables
EXIT WHEN NOT FOUND;
RAISE NOTICE 'shiftid %%%',c_shiftId;
RAISE NOTICE 'activityid %%%',c_activityId;
RAISE NOTICE 'date%%%',c_date;
Update table schemaName.TableB SET TableB.activityId=c_activityId where TableB.date=c_date and TableB.shiftId=c_shiftId; ---Update Statement
END LOOP;
Close _curs;
Return 'Y';
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION schemaName.updateactivityid()
OWNER TO postgres;