2016-11-10 46 views
0

我想在DB2版本11.1.0中使用CTAS語句,它創建一個新表並插入它。查詢如下:DB2 CTAS令牌錯誤

 CREATE TABLE MY_SCRATCH.LC$U7OB81478732948714_zero_to_3 AS (
     WITH two AS (SELECT id AS the_num FROM users WHERE id = 2) 
     , one_two AS (
     SELECT id AS the_num FROM users WHERE id = 1 
     UNION ALL 
     SELECT * FROM two tmp 
    ) 
     , zero_one_two AS (
     SELECT id-7 AS the_num FROM users where id = 7 
     UNION ALL 
     SELECT * FROM one_two tmp 

    ) 
     SELECT * FROM zero_one_two tmp 
     UNION ALL 
     SELECT id AS the_num FROM users WHERE id = 3 
    ) WITH DATA 

不過,我收到以下錯誤:

"my_error":"SQL Error: derived_table zero_to_3 creation failed: SQL Error in CREATE TABLE as SELECT: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=AS;RO_TO_3\" (\nWITH TWO;JOIN, DRIVER=4.16.53"

DB2 docs,錯誤是因爲以下幾點:

A syntax error was detected where the symbol "token" occurs in the SQL statement. The list of symbols that might be legal shows some alternate symbols that could possibly be correct at that point, if the preceding part of the statement is entirely correct.

所以我在RazorSQL中運行上述查詢,並且拋出了相同的錯誤。不太確定令牌問題的位置是

+0

包括列名稱的預期表結構是什麼? –

回答

2

您不能使用公用表表達式。如果你看一下語法CREATE TABLE(下圖刪節爲您的具體問題):

>>-CREATE TABLE--table-name-------------------------------------> 

>--+-----------------------+--AS--(--fullselect--)--------------> 
    | .-,-----------. |       
    | V    | |       
    '-(----column-name-+--)-'       

>--+-WITH NO DATA-+---------------------------------------------| 
    '-WITH DATA----' 

一個fullselect是一個充滿選擇查詢的一部分,但它不包括公共表表達式。公用表表達式是select-statement的一部分。

使用嵌套表表達式而不是通用表表達式重寫您的查詢是可能的,但是對於您的示例查詢,如果您甚至根本不需要公用表表達式,則很難說明這一點。您的查詢可以用更簡單的方式寫成:

CREATE TABLE MY_SCRATCH.LC$U7OB81478732948714_zero_to_3 AS (
    select id as the_num from users where id = 2 
    union all 
    select id as the_num from users where id = 1 
    union all 
    select id-7 as the_num from users where id = 7 
    union all 
    select id as the_num from users where id = 3 
) 
    WITH DATA; 
+0

我沒有最終使用你的代碼,因爲我在我的系統中發現了一個標誌,允許我關閉CTAS中的CTE修復問題 – theGreenCabbage