2016-02-25 62 views
0

我試圖運行代碼:如何通過表名PLPGSQL功能

CREATE OR REPLACE FUNCTION anly_work_tbls.testfncjh (tablename text) returns int 
AS $$ 
DECLARE 
     counter int; 
     rec record; 
     tname text; 
BEGIN 
counter = 0; 
tname := tablename; 
FOR rec IN 
     select * 
     from tname 
    loop 
     counter = counter + 1; 
    end loop; 
RETURN counter; 
END; 
$$ 
LANGUAGE 'plpgsql' IMMUTABLE 
SECURITY DEFINER; 

這段代碼的目標是回到表中你輸入的行數。我知道這可能不是完成這個任務的最好方式,但是這個功能的結構可以很好地擴展到我想要解決的另一個問題。每次我運行代碼,我得到的錯誤:

ERROR: syntax error at or near "$1" 

我發現所有的網上資源,告訴我如何使用內EXECUTE塊的輸入變量,而不是在出現上述情況。

當前正在運行的PostgreSQL 8.2.15。

回答

0

是真的不是最好的方式,但是這會工作:

CREATE OR REPLACE FUNCTION testfncjh (tablename text) returns int 
AS $$ 
DECLARE 
     counter int; 
     rec record;   
BEGIN 
counter = 0; 
FOR rec IN 
     EXECUTE 'select * from '||quote_ident(tablename) loop 
     counter = counter + 1; 
    end loop; 
RETURN counter; 
END; 
$$ 
LANGUAGE 'plpgsql' IMMUTABLE 
SECURITY DEFINER; 

這會更好:

CREATE OR REPLACE FUNCTION testfncjh (tablename text) returns int 
AS $$ 
DECLARE _count INT; 
BEGIN  
EXECUTE 'SELECT count(*) FROM '|| quote_ident(tablename) INTO _count; 
RETURN _count; 
END; 
$$ 
LANGUAGE 'plpgsql' IMMUTABLE 
SECURITY DEFINER; 
+0

謝謝,這是有益的。 – JHoffman

1
CREATE OR REPLACE FUNCTION anly_work_tbls.testfncjh (tbl regclass, OUT row_ct int) AS 
$func$ 
BEGIN  
    EXECUTE 'SELECT count(*) FROM '|| tbl 
    INTO row_ct; 
END 
$func$ LANGUAGE plpgsql IMMUTABLE SECURITY DEFINER; 

電話:

SELECT anly_work_tbls.testfncjh('anly_work_tbls.text_tbl'); 

這應該爲Postgres 8.2工作,但你無論如何,。

如果你實際上是通過動態查詢的結果需要循環:

CREATE OR REPLACE FUNCTION anly_work_tbls.testfncjh (tbl regclass) 
    RETURNS int AS 
$func$ 
DECLARE 
    counter int := 0; -- init at declaration time 
    rec record; 
BEGIN 
    FOR rec IN EXECUTE 
     'SELECT * FROM ' || tbl 
    LOOP 
     counter := counter + 1; -- placeholder for some serious action 
    END LOOP; 

    RETURN counter; 
END 
$func$ LANGUAGE plpgsql IMMUTABLE SECURITY DEFINER; 
+0

謝謝,這工作! – JHoffman