首页 新闻 赞助 找找看

如何在cursor中使用cte?

0
悬赏园豆:50 [已解决问题] 解决于 2014-12-23 12:50

CTE用起来很方便,但是,发现WITH后必须跟着select,想把WITH的结果应用到存储过程则失败,比如:

正确用法:

with cte as
   select * from table1
   union all
      select table1.* from table1, cte
         where table1.parentid=cte.id
select * from cte;

换成cursor失败:

with cte as
   select * from table1
   union all
      select table1.* from table1, cte
         where table1.parentid=cte.id
declare mycursor cursor for select * from cte;

请问有什么办法达成这个目的?

谢谢!

519740105的主页 519740105 | 大侠五级 | 园豆:5810
提问于:2014-12-22 15:17
< >
分享
最佳答案
0

你可以考虑把CTE结果Insert到一个临时表里面啊。

 

另外,CURSOR是你写错顺序了。

收获园豆:40
爱编程的大叔 | 高人七级 |园豆:30839 | 2014-12-22 15:28
其他回答(1)
0
--临时表
 IF OBJECT_ID ('tempdb..#cte') IS NOT NULL
 BEGIN
    DROP TABLE #cte;
 END;
with cte as select * from table1 union all select table1.* from table1, cte where table1.parentid=cte.id
select * into #cte from cte;
 
 IF OBJECT_ID ('tempdb..#cte') IS NOT NULL
 BEGIN
    DROP TABLE #cte;
 END;
收获园豆:10
KingMi | 园豆:1344 (小虾三级) | 2014-12-22 16:21
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册