--with用法 --能夠這麼理解 with SQL語句變量或者叫臨時表名 as( SQL語句 ) select * from SQL語句變量或者叫臨時表名
--遞歸調用 with CTE as( select ZTBM_ID,ztbm_name,ParentId from TB_ZYM_ZTBM where ParentId is null or ParentId='' union all select a.ZTBM_ID,a.ztbm_name,a.ParentId from TB_ZYM_ZTBM a inner join CTE on a.ParentId=CTE.ZTBM_ID ) select * from CTE --此語句能夠理解以下
--同上一個語句 --最頂層 1 select ZTBM_ID,ztbm_name,ParentId from TB_ZYM_ZTBM where ParentId is null or ParentId='' union all select a.ZTBM_ID,a.ztbm_name,a.ParentId from TB_ZYM_ZTBM a inner join --此處括弧能夠理解爲最頂層的CTE 此處紅色CTE即上一個SQL語句的CTE ( --第二層 select ZTBM_ID,ztbm_name,ParentId from TB_ZYM_ZTBM where ParentId is null or ParentId='' union all select a.ZTBM_ID,a.ztbm_name,a.ParentId from TB_ZYM_ZTBM a inner join --此處括弧能夠理解爲第二層的CTE ( --第三層 select ZTBM_ID,ztbm_name,ParentId from TB_ZYM_ZTBM where ParentId is null or ParentId='' union all select a.ZTBM_ID,a.ztbm_name,a.ParentId from TB_ZYM_ZTBM a inner join ( --第四層 select ZTBM_ID,ztbm_name,ParentId from TB_ZYM_ZTBM where ParentId is null or ParentId='' union all select a.ZTBM_ID,a.ztbm_name,a.ParentId from TB_ZYM_ZTBM a inner join ( select ZTBM_ID,ztbm_name,ParentId from TB_ZYM_ZTBM where ParentId is null or ParentId='' --inner join.... 層層嵌套 --最底層 ) CTE on a.ParentId=CTE.ZTBM_ID ) CTE on a.ParentId=CTE.ZTBM_ID ) CTE on a.ParentId=CTE.ZTBM_ID ) CTE on a.ParentId=CTE.ZTBM_ID
變異以下查詢(排序,及分割)spa
with CTE as ( -->Begin 一個定位點成員 select ZTBM_ID, ztbm_name,ParentId,cast(ztbm_name as nvarchar(max)) as TE, ROW_NUMBER()over(order by getdate()) as OrderID,0 as Levle from TB_ZYM_ZTBM where deleteMark=1 and (ParentId is null or ParentId='') -->End union all -->Begin一個遞歸成員 select TB_ZYM_ZTBM.ZTBM_ID, TB_ZYM_ZTBM.ztbm_name,TB_ZYM_ZTBM.ParentId,cast(replicate(' ',Levle+1)+'|_'+TB_ZYM_ZTBM.ztbm_name as nvarchar(MAX)) as TE, CTE.OrderID*100+ROW_NUMBER()over(Order by GETDATE()) as OrderID ,Levle+1 as Levle from TB_ZYM_ZTBM inner join CTE on TB_ZYM_ZTBM.ParentId=CTE.ZTBM_ID -->End ) select * from CTE order by LTRIM(OrderID)
參考:http://blog.csdn.net/bin_520_yan/article/details/5998349.net
http://msdn.microsoft.com/zh-cn/library/ms175972(SQL.105).aspxcode