sqlserver with 语法

with
cte1 as
(
select * from table1 where name like 'abc%'
),
cte2 as
(
select * from table2 where id > 20
),
cte3 as
(
select * from table3 where price < 100
)
select a.* from cte1 a, cte2 b, cte3 c where a.id = b.id and a.id = c.id

请问一下这个语句那里有错,在sql查询分析器中报错:
消息 156,级别 15,状态 1,第 1 行
在关键字 'with' 附近有语法错误。
消息 170,级别 15,状态 1,第 2 行
第 2 行: ',' 附近有语法错误。
我就是在查询分析器中单独执行。

一.sqlserver with as的含义
  WITH AS短语,也叫做子查询部分(subquery factoring),可以让你做很多事情,定义一个SQL片断,该SQL片断会被整个SQL语句所用到。有的时候,是为了让SQL语句的可读性更高些,也有可能是在UNION ALL的不同部分,作为提供数据的部分。
  特别对于UNION ALL比较有用。因为UNION ALL的每个部分可能相同,但是如果每个部分都去执行一遍的话,则成本太高,所以可以使用WITH AS短语,则只要执行一遍即可。如果WITH AS短语所定义的表名被调用两次以上,则优化器会自动将WITH AS短语所获取的数据放入一个TEMP表里,如果只是被调用一次,则不会。而提示materialize则是强制将WITH AS短语里的数据放入一个全局临时表里。很多查询通过这种方法都可以提高速度。
二.使用方法
  先看下面一个嵌套的查询语句:
  select * from person.StateProvince where CountryRegionCode in
  (select CountryRegionCode from person.CountryRegion where Name like 'C%')
  declare @t table(CountryRegionCode nvarchar(3))
  insert into @t(CountryRegionCode) (select CountryRegionCode from person.CountryRegion where Name like 'C%')
  select * from person.StateProvince where CountryRegionCode
  in (select * from @t)
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-11-11
在with前面加个分号(;)
;with
cte1 as ...

如果不加分号,单独执行应该没有问题。
如果是作为批处理的一部分,那必须加分号;

补充:
CTE是SQL2005新增的功能,SQL2000不支持CTE。本回答被提问者采纳
相似回答