如何基于PostgreSQL 8.3.16上的plpgsql指令循环更新表?

时间:2015-04-23 18:48:43

标签: sql postgresql

我遇到了一个问题我到目前为止还不确定如何解决它...

我有两个彼此相关的表,其关系为1 x n。我将尝试描述下面更重要的字段:

表一 - 公司:id PK,companyname varchar;
表二 - 培训:课程varchar,companyid bigint FK,id PK;

问题是:我想更新表格培训课程领域的信息,因为有许多相同名称的课程。我的想法是使用像

这样的东西
for s in 1..n loop 
update training set course = course || s;
end loop;

3 个答案:

答案 0 :(得分:0)

不需要使用纯SQL执行此操作的循环:

with numbered as (
   select id, 
          row_number() over (order by id) as rn
   from training
)
update training 
   set course = course||n.rn::text
from numbered n
where n.id = training.id;

common table expressiontraining表格中的每一行指定一个数字,然后使用该数字生成新的课程名称。

答案 1 :(得分:0)

UPDATE training
SET course = course || num
FROM (
    SELECT generate_series(1, (
                SELECT count(course)
                FROM training
                )) num
    ) t

答案 2 :(得分:0)

我解决了我的疑问,在下面创建了这个函数:

创建或替换功能 changeName()
退回作为
$$
DECLARE
table1id table1.id%TYPE ;
counter1 记录;
counter2 记录;

BEGIN
FOR
counter1 IN SELECT
repeated_column,foreign_keyid COUNT repeated_column AS contagem
FROM table1 GROUP BY repeated_column,foreign_keyid 有计数(< i> repeated_column )&gt; 1 LOOP
FOR
counter2 IN 1 .. counter1.contagem LOOP
SELECT id INTO table1id FROM table1 WHERE repeated_column
IN
counter1.repeated_column AND foreign_keyid = counter1.foreign_keyid ;
更新 table1 SET repeated_column = repeated_column || &#39; (&#39; || counter2 ||&#39;)&#39; WHERE id = table1id ;
END LOOP;
结束循环;
END;

$$
LANGUAGE &#39; plpgsql&#39;