如何基于含WITH子句的查询创建表?解决语法报错问题
基于包含WITH子句的查询创建表的方法
可以基于包含WITH子句(公共表表达式CTE)的查询创建表,你之前的写法报错是因为CTE的位置不符合SQL Server的语法规则。
原查询示例
with test as ( select 999 as col1 ) select * from test;
你尝试的错误写法及报错
select * into newtable from ( with test as( select 999 as col1 ) select * from test ) as newtable
报错信息:
Msg 319, Level 15, State 1, Line 3 Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause
正确写法
SQL Server要求CTE必须作为语句的起始部分(或在分号之后,但更规范的是放在开头),不能嵌套在子查询内部。针对你的需求,有两种标准写法:
写法1:直接将CTE放在SELECT ... INTO前
with test as ( select 999 as col1 ) select * into newtable from test;
写法2:适配复杂多层CTE场景
如果你的实际查询包含多个嵌套或关联的CTE,可以按顺序定义所有CTE后再执行SELECT ... INTO:
with cte1 as ( select 999 as col1 ), cte2 as ( select col1 from cte1 where col1 > 500 ) select * into newtable from cte2;
这两种写法都能绕过你遇到的语法错误,同时保留CTE的逻辑结构,适配复杂查询需求。
内容的提问来源于stack exchange,提问作者Osy
相关产品推荐
相关产品推荐

