0

我有使用 FOR 循环和动态查询的功能。不知道为什么,但 postgres 无法从记录变量中检索单个字段...仍然出现错误

SELECT (1,token).id - syntax error?

有没有机会从中获得字段值?

CREATE OR REPLACE FUNCTION mobile666(v_limit integer, v_offset integer) RETURNS void AS
$BODY$
  DECLARE
    r record;
    x text[];
    kap text;
    i_attrs text[] := ARRAY[
    ['test','id','value'],
    ['test', 'id','value'],
    ['test', 'id','value'],
    ['test', 'id','value']
    ];
    quer text;

  BEGIN
    FOREACH x SLICE 1 IN ARRAY i_attrs LOOP
   FOR r in EXECUTE
    'SELECT * FROM ' || x[1]::regclass || ' WHERE ' || quote_ident(x[2]) || ' IS NOT NULL'  LOOP

  execute 'SELECT '|| r || '.' || quote_ident(x[2]) INTO kap;
     RAISE NOTICE 'id %', kap;
execute 'SELECT '|| r || '.' || quote_ident(x[5]) INTO kap;
     RAISE NOTICE 'id %', kap;

  END LOOP;
  END LOOP;

    END;
  $BODY$
LANGUAGE plpgsql VOLATILE
COST 400;



CREATE TABLE test
(
  id integer NOT NULL,
  value text NOT NULL,
  CONSTRAINT pk_test PRIMARY KEY (id )
)
WITH (
  OIDS=FALSE
);


INSERT INTO test(
            id, value)
    VALUES (1,'token'),(2,'smt'),(3,'cocc');
4

1 回答 1

0

试试这个:

CREATE OR REPLACE FUNCTION mobile666(v_limit integer, v_offset integer) RETURNS void AS
$BODY$
DECLARE
    r record;
    x text[];
    kap text;
    i_attrs text[] := ARRAY[
    ['test','id','value'],
    ['test', 'id','value'],
    ['test', 'id','value'],
    ['test', 'id','value']
    ];
    quer text;

BEGIN
    FOREACH x SLICE 1 IN ARRAY i_attrs LOOP
        FOR r in EXECUTE
            'SELECT * FROM ' || x[1]::regclass || ' WHERE ' || quote_ident(x[2]) || ' IS NOT NULL'  LOOP

            execute 'SELECT ($1::text::' || x[1] || ').' || x[2] INTO kap USING r;
            RAISE NOTICE 'id %', kap;
            execute 'SELECT ($1::text::' || x[1] || ').' || x[3] INTO kap USING r;
            RAISE NOTICE 'id %', kap;
        END LOOP;
    END LOOP;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 400;

线索是将动态 sql 字符串中的记录r( ) 转换为适当的表 ( )。在此之后,您可以访问记录列,您可以动态更改表名或列名。$1$1::text::table_name($1::text::table_name).col_name

于 2013-04-30T12:58:48.957 回答