2016-01-13 61 views
0

我有以下聲明,我想根據它的一些列條目來更新表。我使用Firebird 2.1,文檔顯示更新可以與CTE一起使用,但是我的flamerobin固執地堅持認爲update語句不被識別。你能對此有所瞭解嗎?更新聲明與CTE(火鳥2.1)

with cte as (select gen_id(gen_new,1) as num , N.elm_prof, N.elm_mat From 
(select distinct elm_mat, elm_prof from elements) N) 
update elements E set E.PROP_TYPE = cte.num where cte.elm_prof = E.ELM_PROF and cte.elm_mat = E.ELM_MAT 

Engine Message : 
Dynamic SQL Error 
SQL error code = -104 
Token unknown - line 3, column 1 
update 


merge into elements E1 
using (with CTE as (select distinct e2.ELM_MAT mat1, e2.ELM_PROF mat2 from elements e2) 
select gen_id(gen_new,1) num, mat1, mat2 from cte) 
on E1.elm_mat = mat1 and e1.elm_prof = mat2 
when matched then update set e1.prop_type = num 

回答

1

在文檔中哪裏顯示更新可以與CTE一起使用?當我看Common Table Expressions,它說

<cte-construct> ::= <cte-defs> 
         <main-query> 

<main-query>  ::= the main SELECT statement, which can refer to the 
         CTEs defined in the preamble 

即只select是允許的main-query。我想你該語句

當用括號括起來困惑,CTE結構可作爲在SELECT語句子查詢,而且在更新,合併等

在doc以後。據我瞭解,這意味着你可以使用類似的語句

UPDATE elements E 
    SET E.PROP_TYPE = (CTE statement here) WHERE... 

注意,CTE必須選擇在這種情況下一個singelton。

+0

好的,我完全迷惑於你所表明的那種陳述。如果CTE的返回值是數據集(這是我的情況)而不是單例,那麼問題就出現了,任何解決方法,我不限於CTE表達式,任何滿足更新任務的其他選項都是很好的。 –

+0

我想你可以使用MERGE語句,參見http://www.firebirdsql.org/file/documentation/reference_manuals/reference_material/html/langrefupd21-merge.html或者也許只是將邏輯包裝到一個存儲過程中,您可以使用各種使邏輯更容易理解的構造。 – ain

+0

我也嘗試用合併語句更新問題中顯示的代碼。我認爲它不接受CTE作爲子查詢語句。請注意,我使用發生器,所以這可能是造成差異的原因。 –