2016-04-28 56 views
0

該片段是函數中的一部分,它將一個整數(和ID)和一個字符串(一個表名)作爲indata,稱爲$ 1和$ 2。在第一個示例中,由於當前的功能起作用,輸入將爲(68, 'heat_arcs')並且該功能起作用。但是,該功能需要擴展以適應不同的表格,所以我想我可以將cost FROM heat_arcs'更改爲cost FROM ' || $2 ||',但由於「未端接引用的字符串」,這會產生語法錯誤。使用管道連接字符串時的行爲不一致

爲什麼我可以在查詢的後面部分成功地將字符串與輸入數據連接起來,但不是在早期部分? pgr_trsp請求字符串作爲輸入的第一和最後一個參數

電流:

FROM pgr_trsp(
       'SELECT gid as id, source, target, cost FROM heat_arcs', 
       r, 2, false, false, 'select 1000 as to_cost, b.target_id, a.via_path::text from 
    (select gid as target_id from '|| $2 ||' where source = ' || $1 ||' or target = ' || $1 ||') as b, 
    (select gid as via_path from '|| $2 ||' where source = ' || $1 ||' or target ='|| $1 ||') as a WHERE b.target_id <> a.via_path' 

期望:

FROM pgr_trsp(
       'SELECT gid as id, source, target, cost FROM '|| $2 ||', 
       r, 2, false, false, 'select 1000 as to_cost, b.target_id, a.via_path::text from 
    (select gid as target_id from '|| $2 ||' where source = ' || $1 ||' or target = ' || $1 ||') as b, 
    (select gid as via_path from '|| $2 ||' where source = ' || $1 ||' or target ='|| $1 ||') as a WHERE b.target_id <> a.via_path' 

回答

0

你會踢自己在這一個:你有流浪的引號!如果你仔細觀察,你的問題(和你的編輯器)中的語法突出顯示。

在我們有一個字符串,一個逗號,文字r工作版本:

'SELECT gid as id, source, target, cost FROM heat_arcs', r 

在破碎的版本,我們有包含逗號和R A字符串:

'SELECT gid as id, source, target, cost FROM '|| $2 ||', r 

取出級聯,這就是:

'SELECT gid as id, source, target, cost FROM heat_arcs, r 

所以你真正想要的是:

'SELECT gid as id, source, target, cost FROM '|| $2, r 

注意,因爲你正在創建動態SQL,你應該確保使用正確的quoting functions(以及健全檢查針對白名單的說法,理想):

'SELECT gid as id, source, target, cost FROM '|| quote_ident($2), r 
+0

非常感謝,IMSoP。我也會接受你的建議,並檢查引用函數:) – FHilding