2013-10-10 29 views
2

我解決不了這個無參數$ 1:PL/pgSQL的存在EXECUTE語句

CREATE OR REPLACE FUNCTION dpol_insert(
    dpol_cia integer, dpol_tipol character, dpol_nupol integer, 
    dpol_conse integer,dpol_date timestamp) 
    RETURNS integer AS 
$BODY$ 
    DECLARE tabla text := 'dpol'||EXTRACT (YEAR FROM $5::timestamp); 
BEGIN 
    EXECUTE ' 
    INSERT INTO '|| quote_ident(tabla) ||' 
    (dpol_cia, dpol_tipol, dpol_nupol, dpol_conse, dpol_date) VALUES ($1,$2,$3,$4,$5) 
    '; 
END 
$BODY$ 
    LANGUAGE plpgsql VOLATILE 
    COST 100; 

當試圖

SELECT dpol_insert(1,'X',123456,1,'09/10/2013') 

返回一條消息:

ERROR: there is no parameter $1 
LINE 3: ...tipol, dpol_nupol, dpol_conse, dpol_date) VALUES ($1,$2,$3,$... 
                  ^
QUERY: 
    INSERT INTO dpol2013 
    (dpol_cia, dpol_tipol, dpol_nupol, dpol_conse, dpol_date) VALUES ($1,$2,$3,$4,$5) 

CONTEXT: PL/pgSQL function "dpol_insert" line 4 at EXECUTE statement 

*** 錯誤 ** *

ERROR: there is no parameter $1 
SQL state: 42P02 
Context: PL/pgSQL function "dpol_insert" line 4 at EXECUTE statement 

回答

6

你這裏有幾個問題。眼前的問題是:

ERROR: there is no parameter $1

這是因爲$1,你遞給執行SQL裏面是不一樣的$1主要功能體內。在執行SQL中的佔位符編號在上下文的EXECUTE,而不是在功能的情況下,所以你需要提供一些參數EXECUTE這些佔位符:

execute '...' using dpol_cia, dpol_tipol, dpol_nupol, dpol_conse, dpol_date; 
--   ^^^^^ 

Executing Dynamic Commands手冊中的細節英寸

接下來的問題是,你沒有從你的函數返回任何東西RETURNS integer。我不知道你打算返回什麼,但也許你的tablea有你想要返回的SERIAL id。如果是這樣,那麼你想要更像這樣的東西:

declare 
    tabla text := 'dpol' || extract(year from $5::timestamp); 
    id integer; 
begin 
    execute 'insert into ... values ($1, ...) returning id' into id using dpol_cia, ...; 
    --          ^^^^^^^^^^^^ ^^^^^^^ 
    return id; 
end 

在你的功能。

+0

非常感謝! – stefmex

+0

@mu太短:這是我在我的SQL函數中得到的錯誤。我還沒有能夠解決它,也許你有一些指針? -謝謝! http://stackoverflow.com/questions/19918385/calling-a-stored-procedure-within-a-stored-procedure –

相關問題