2015-11-11 73 views
2

我有一個表(名爲VGI_table),其中包含一個列(名爲match_tabl),該列包含同一數據庫中的其他表的名稱以及這些表的object_ids 。我試圖創建一個plpgsql函數,循環遍歷VGI_table中的每一行,並執行查詢以從另一個表中檢索對象,如下所示。Postgres- SQL狀態:22004 - EXECUTE的查詢字符串參數爲空

該函數需要4個參數(所有varchar),前兩個是VGI_table中的列名稱,第三個是VGI_table的名稱,最後一個參數是輸出。

vgi_match_id_col, vgi_match_table_col, vgi_table, output_table 

該函數的代碼如下所示,RO是用於保持第一表查詢,match_row保持查詢外部表的輸出。距離是使用PostGIS st_distance函數創建的輸出。

DECLARE 
    ro record; 
    match_row record; 
    distance float; 

BEGIN 

for ro in EXECUTE 'select gid, geom, '||vgi_match_id_col||' as match_id, '||vgi_match_table_col||' as match_table from '||vgi_table 
LOOP 
    --raise notice '(%)', 'select geom from public.'||ro.match_table||' where gid = '||ro.match_id; 


    execute 'select geom from public.'||ro.match_table||' where gid = '||ro.match_id into match_row; 


    distance := st_distance(ro.geom, st_transform(match_row.geom,st_srid(ro.geom))); 
    EXECUTE 'INSERT INTO '||output_table||' VALUES('||ro.gid||', '||distance||')'; 


END LOOP; 

被查詢的表在match_tabl列或object_id列中沒有空值。代碼在嘗試執行EXECUTE語句時將ro.match_table和ro.match_id標識爲空值。我甚至使用了與EXECUTE語句中使用的字符串相同的RAISE NOTICE函數,並返回了正確的查詢。如果我用預定義的table_name和對象id硬編碼執行字符串,那麼腳本就可以正常工作。下面的鏈接是相似的,但我不認爲它解決了我的問題。謝謝您的幫助。

Similar Question

回答

3

好吧,很顯然你串聯的東西是空的。

改用format函數,這樣你會得到更多有用的信息。

format('select geom from public.%I ....', ro.match_table); 

使用EXECUTE ... USING ...來插入文字。

例如

EXECUTE format('INSERT INTO %I VALUES($1, $2)', output_table) USING (ro.gid, distance); 
+0

感謝您的快速響應和幫助。它實際上是包含NULL輸出的距離函數,它是拋出錯誤的第二個執行。包括USING函數轉義了NULL值。再次感謝您的幫助。 – Maju

0

Postgres裏,如果有什麼空在動態DML傳遞,我們必然要得到這個問題。「執行的查詢字符串參數爲空」 您可以使用下面的示例步驟,插入和更新。

CREATE OR REPLACE FUNCTION samplefunc(

    col1param character varying, 
    col2param character varying, 
    col3param character varying, 
    col4param character varying, 
    col5param character varying, 
    col6param character varying, 
    col7param character varying, 
    col8param character varying 

    RETURNS boolean AS 

$BODY$ 

declare 

begin 

EXECUTE format('insert into '||tablename||' (id, col1, col2, col3, col4, col5)values($1,$2,$3,$4,$5)') USING col1param ,col2param,col3param,col4param,col5param; 


EXECUTE format('update '||tablename||' set col1 =$1,col2 = $2,col3=$3,col4=$4,col5=$5 
where col6=$6 and col7=$7 and col8=$8 ') using col1param,col2param,,col3param,col4param,col5param,col6param,col7param,col8param; 

end