0

以下函数在运行时会报错

我注意到,当我删除这条线时AND t.image_id = mviews.image_id ,它会起作用。

即使我将 mviews.image_id 更改为常数,它也可以工作

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

0000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000

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;

0000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000

********** 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

0000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000

4

1 回答 1

2

您的问题是COPY无法执行动态 SQL。该变量mviews在 的查询中不可见COPY。您需要动态 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;

我大量使用美元报价来简化报价处理。

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

于 2012-05-15T15:03:55.360 回答