日期:2014-05-18  浏览次数:20598 次

sql2008 递归,客户端with语法错误
今天在SQL2008试了一个普通的递归SQL,在服务器端没问题,
但在客户端显示with语法错误,请教什么原因?
客户端是XP操作系统
WITH lmenu(name,senior,level) as
(
SELECT NAME,SENIOR,0 level FROM MENU WHERE SENIOR IS NULL
UNION ALL
SELECT A.NAME,A.SENIOR,b.level+1 FROM MENU A,lmenu b
where a.senior = b.name
)
SELECT * from lmenu


------解决方案--------------------
with 前加个;号看。
------解决方案--------------------
SQL code

WITH lmenu(name,senior,level) as
(
SELECT NAME,SENIOR,0 level FROM MENU WHERE SENIOR IS NULL
UNION ALL
SELECT A.NAME,A.SENIOR,b.level+1 FROM MENU A,lmenu b
where a.senior = b.name
)
SELECT * from lmenu

--你这个是递归吗?


给你一个递归的例子,最基础的递归:

--> 测试数据:[tbl]
go
if object_id('[tbl]') is not null 
drop table [tbl]
go
create table [tbl](
[name] varchar(1),
[date] varchar(5),
[num] int
)
go
insert [tbl]
select 'a','1-1号',1 union all
select 'b','1-2号',4 union all
select 'a','1-3号',8 union all
select 'a','1-4号',5 union all
select 'b','1-5号',6 union all
select 'b','1-6号',9

;with t
as(
select ROW_NUMBER()over(partition by name
order by [date]) as id,
*,num  as total from tbl
),
m as(
select id,name,[date],num,total from t where id=1
union all
select a.id,a.name,a.[date],a.num,b.total+a.num from t a
inner join m b on a.id=b.id+1 and a.name=b.name
)
select name,[date],num,total from m order by name

/*
name    date    num    total
a    1-3号    8    8
a    1-4号    5    13
a    1-1号    1    14
b    1-2号    4    4
b    1-5号    6    10
b    1-6号    9    19
*/