2013-04-30 87 views
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'); 
+1

請始終顯示您的PostgreSQL版本和錯誤的* full *,* exact *文本。如果重寫它以使用'format'函數的'%I'(標識符)格式說明符'EXECUTE ... USING',則可能會發現此代碼更易於理解。 – 2013-04-30 12:57:59

回答

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字符串適當的表格($1::text::table_name)內記錄r$1)。在此之後,您可以訪問像($1::text::table_name).col_name這樣的記錄列,並且可以動態更改表名或列名。

+0

是的,thx,它的工作原理;) – Borys 2013-04-30 13:21:06