从递归查询错误中查看

时间:2018-08-28 07:10:18

标签: sql-server view syntax-error common-table-expression

我有一个运行良好的递归查询:

with cte as (
         select ps.SetProduct from PRODSET ps
         left join PRODUCT pr on pr.Product= ps.Product
         where ...

         union all

         select ps.SetProduct from PRODSET ps
         inner join cte on ps.Product= cte.SetProduct
         )

select distinct cte.SetProduct from cte

添加“创建视图”会在最后一行给出错误“关键字'SET'附近的语法不正确”。我什至没有使用SET。

整个代码:

create view wiev_product as

with cte as (
         select ps.SetProduct from PRODSET ps
         left join PROD pr on pr.Product= ps.Product
         where ...

         union all

         select ps.SetProduct from PRODSET ps
         inner join cte on ps.Product= cte.SetProduct
         )

select distinct cte.SetProduct from cte

我正在处理MS SQL服务器使用了未指定的ERP系统。是ERP的限制,还是我的查询有问题?

我可以尝试在代码中进行任何变通吗?

谢谢。

编辑:Microsoft SQL Server 2012(SP1) 错误156没有; as with 错误102;之间;与cte

1 个答案:

答案 0 :(得分:0)

这是ERP的局限性。我没有从cte创建视图,也没有在第二个查询中使用该视图作为条件,而是设法在单个查询中使用两个cte来完成所有操作。

with cte1 as (
         select ps.SetProduct from PRODSET ps
         left join PRODUCT pr on pr.Product= ps.Product
         where ...

         union all

         select ps.SetProduct from PRODSET ps
         inner join cte on ps.Product= cte.SetProduct
         ),

    cte2 as (
         select ps.SetProduct from PRODSET ps
         left join PRODUCT pr on pr.Product= ps.Product
         where ...

         union all

         select ps.SetProduct from PRODSET ps
         inner join cte on ps.Product= cte.SetProduct
         )

select distinct cte1.SetProduct from cte1
where cte1.SetProduct not in (select ... from cte2 where ...)