我试图在DB2版本11.1.0中使用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错误:derived_table zero_to_3创建失败:CREATE TABLE中的SQL错误为SELECT:com.ibm.db2.jcc.am.SqlSyntaxErrorException:DB2 SQL错误:SQLCODE = -104,SQLSTATE = 42601,SQLERRMC = AS; RO_TO_3 \“(\ nWITH TWO; JOIN,DRIVER = 4.16.53”
根据DB2 docs,错误是由于以下原因:
检测到语法错误,其中符号“token”出现在SQL语句中。如果语句的前一部分完全正确,那么可能合法的符号列表会显示一些在该点可能正确的替代符号。
所以我在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;