Newbee的Postgres功能

时间:2012-05-15 13:07:38

标签: function postgresql loops

以下函数将在运行时给出错误

我注意到当我删除此行时AND t.image_id = mviews.image_id 有用。

即使我将mviews.image_id更改为常数也可以

我在想我没有正确引用循环参数?

000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000

CREATE OR REPLACE FUNCTION test() RETURNS void AS $$
  DECLARE
    mviews RECORD;     
BEGIN        
FOR mviews IN 
SELECT image_id FROM image_index_1205 WHERE image_type = '01' LIMIT 3
LOOP
copy    (

    SELECT encode(decode(image, 'base64'), 'hex') 
    FROM image_index_1205 t
    WHERE image_type = '01'
    AND t.image_id =  mviews.image_id
    LIMIT 1
    ) 
TO
    '/tmp/test.hex';

END LOOP;   
END;
$$ LANGUAGE plpgsql;

000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000

********** Error **********

ERROR: there is no parameter $1
SQL state: 42P02
Context: SQL statement "copy ( SELECT encode(decode(image, 'base64'), 'hex') FROM image_index_1205 t WHERE image_type = '01' AND t.image_id =  $1  LIMIT 1 ) TO '/tmp/test.hex'"
PL/pgSQL function "test" line 7 at SQL statement

000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000

1 个答案:

答案 0 :(得分:2)

您的问题是COPY无法执行动态SQL。变量mviewsCOPY的查询中不可见。你需要动态SQL。构建查询字符串并使用EXECUTE。像这样:

CREATE OR REPLACE FUNCTION test()
  RETURNS void AS
$BODY$
DECLARE
    mviews RECORD;     
BEGIN        

FOR mviews IN 
    SELECT image_id FROM image_index_1205 WHERE image_type = '01' LIMIT 3
LOOP
    EXECUTE $x$
    COPY (
       SELECT encode(decode(image, 'base64'), 'hex') 
       FROM   image_index_1205 t
       WHERE  image_type = '01'
       AND    t.image_id =  $x$ || mviews.image_id || $y$
       LIMIT 1
       ) 
    TO '/tmp/test.hex'
    $y$;
END LOOP;   

END;
$BODY$ LANGUAGE plpgsql;

我大量使用dollar-quoting来简化报价处理。

如果还改变了目标文件,该函数会更有意义。它的方式是,每次迭代都会覆盖之前的迭代,并且只有最后一次循环的结果才会持续存在。动态文件名也需要动态SQL。