现有一临时数据表,需要将里面的数据查询出特定的记录Id并根据id更新到实际表中。现在各种查资料终于拼接起来了这个函数。不过话说,postgres都不区分函数与存储过程的么?都是create function,mysql我记得都是区分开的吧。
SQL开始:前面的声明即为create function updateArea() RETURNS updateRecord AS $$
create function updateArea() RETURNS int AS $$
1 DECLARE updateRecord int; court VARCHAR ; building VARCHAR ; unit VARCHAR ; floors VARCHAR ; room VARCHAR ; tmparea VARCHAR ; roomid INT ; 2 curs1 refcursor ; --声明游标,我之前用cursor报错,然后换refcursor 3 BEGIN 4 OPEN curs1 FOR EXECUTE 'SELECT court,building,unit,FLOOR,room,area FROM sp_temp' ; --这里的execute后接的需要加引号 5 updateRecord := 1; --预定义原始值,orcal的写法 := 6 loop 7 FETCH curs1 INTO court, building,unit,floors,room,tmparea ; 8 SELECT 9 room_id INTO roomid 10 FROM 11 view_structure_all 12 WHERE 13 court_name = court 14 AND building_name = building 15 AND unit_name = unit 16 AND floor_nickname = floors 17 AND room_name = room; 18 if found then --当找到时,当初省略了这句一直在查询,没有结果 19 raise notice '%',roomid; --给与输出提示,%占位符 20 update sp_room set area = CAST(tmparea as DECIMAL(12,4)) where room_id = roomid; 21 updateRecord = updateRecord + 1; 22 else exit; 23 end if; 24 end loop; 25 close curs1; --记得关闭游标 26 return updateRecord; 27 end;
$$ language plpgsql
之前还准备用php来查询然后foreach执行update的,但是决定还是用sql直接写函数,不多写写都忘记咯。