Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

postgresql - EXECUTE...USING statement in PL/pgSQL doesn't work with record type?

I'm trying to write a function in PL/PgSQL that have to work with a table it receives as a parameter.

I use EXECUTE..INTO..USING statements within the function definition to build dynamic queries (it's the only way I know to do this) but ... I encountered a problem with RECORD data types.

Let's consider the follow (extremely simplified) example.

 -- A table with some values.
 DROP TABLE IF EXISTS table1;
 CREATE TABLE table1 (
     code INT,
     descr TEXT
 );

INSERT INTO table1 VALUES ('1','a');
INSERT INTO table1 VALUES ('2','b');


-- The function code. 
DROP FUNCTION IF EXISTS foo (TEXT);
CREATE FUNCTION foo (tbl_name TEXT) RETURNS VOID AS $$
DECLARE 
    r RECORD;
    d TEXT;
BEGIN
    FOR r IN
    EXECUTE 'SELECT * FROM ' || tbl_name
    LOOP
    --SELECT r.descr INTO d; --IT WORK
    EXECUTE 'SELECT ($1)' || '.descr' INTO d USING r; --IT DOES NOT WORK
    RAISE NOTICE '%', d;
END LOOP;

END;
$$ LANGUAGE plpgsql STRICT;

-- Call foo function on table1
SELECT foo('table1');

It output the following error:

ERROR: could not identify column "descr" in record data type

although the syntax I used seems valid to me. I can't use the static select (commented in the example) because I want to dinamically refer the columns names.

So..someone know what's wrong with the above code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's true. You cannot to use type record outside PL/pgSQL space.

RECORD value is valid only in plpgsql.

you can do

EXECUTE 'SELECT $1.descr' INTO d USING r::text::xx;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...