使用%ROWTYPE在postgres函数中循环数据时出现问题

时间:2008-12-22 10:51:35

标签: postgresql function rowtype

我正在尝试在postgres中创建一个函数,该函数从一个表中检索数据并输入到另一个表中。我使用%ROWTYPE类型来存储select语句中的临时数据,然后使用insert语句迭代它但是不成功!以下是我的代码:

CREATE OR REPLACE FUNCTION rm_stock_take_add (icompany character varying, idate character varying) 
  RETURNS character varying AS

$BODY$

DECLARE

    loc_result    CHAR(50);

    -- Declaring a counter to increment for the index
    counter INTEGER;

    -- Declare a variable to hold rows from the stock table.
    row_data rm_stock%ROWTYPE;


BEGIN

     -- Iterate through the results of a query.
    FOR row_data IN 
    SELECT *
    FROM rm_stock 
    --WHERE company = icompany 
    ORDER BY company, rm_sto_code, rm_col_code  

        LOOP

      counter := counter + 1;
/*       
          INSERT INTO rm_stock_take
          ( 
           "stock_ind", "company", "rm_stock_code", "rm_col_code", "rm_dye_lot_num", "rm_take_date", "rm_quantity_theo"
          )
          VALUES 
          ( 
           counter, icompany, row_data.rm_sto_code, row_data.rm_col_code, row_data.rm_dye_lot_num, idate,
               row_data.rm_sto_on_hand_excl
          );

*/      
       END LOOP;



   RETURN counter :: character varying;

END;
$BODY$
 LANGUAGE 'plpgsql'VOLATILE;
ALTER FUNCTION rm_stock_take_add(icompany character varying, idate character varying) OWNER TO postgres;

好的,所以目前我只是想通过使用计数器计算循环量并返回该数字来查看函数是否循环,但它还没有返回任何内容。我无法在网上或任何地方找到有关此类程序的大量信息,如果有人可以帮助或指导我朝着正确的方向前进,我们将不胜感激!

由于

1 个答案:

答案 0 :(得分:6)

搞定了......

如果其他人遇到同样的问题,这里是未来参考的代码!

CREATE OR REPLACE FUNCTION rm_stock_take_add(icompany character varying, idate character varying)
  RETURNS character varying AS
$BODY$


DECLARE
    loc_result CHAR(50);
    counter INTEGER = 1;
    row_data RECORD;

BEGIN
    FOR row_data IN SELECT rm_sto_code, rm_col_code, rm_dye_lot_num, rm_sto_on_hand_excl
    FROM rm_stock 
    WHERE company = icompany 
    ORDER BY company, rm_sto_code, rm_col_code  

    LOOP         
          INSERT INTO rm_stock_take
          ( 
               "stock_ind", "company", "rm_stock_code", "rm_col_code", "rm_dye_lot_num", "rm_take_date", "rm_quantity_theo"
          )
          VALUES 
          ( 
               counter, icompany, row_data.rm_sto_code, row_data.rm_col_code, row_data.rm_dye_lot_num, idate,
               row_data.rm_sto_on_hand_excl
          );   
          counter := counter + 1;

    END LOOP;

    loc_result := 'success';  
    RETURN loc_result ;
END;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE;
ALTER FUNCTION rm_stock_take_add(icompany character varying, idate character varying) OWNER TO postgres;