当前位置:Gxlcms > 数据库问题 > SQL 递归使用

SQL 递归使用

时间:2021-07-01 10:21:17 帮助过:5人阅读

直接贴代码吧= =

WITH CTE AS  
  (  
  -->Begin 一个定位点成员  
   SELECT COUNTRYORDERID,HSNAME, COUNTRYNAME,PARENTORDERID,
   IMPORTCURRENTSUMAMOUNT,
   IMPORTCONTRASTSUMAMOUNTPERCENTAGE,
   IMPORTCURRENTSUMAMOUNTPERCENTAGE,
   CAST(COUNTRYNAME AS NVARCHAR(max)) AS TE,0 AS Levle FROM #TempTableDetail
    WHERE PARENTORDERID IS NULL AND HSNAME IN (SELECT HSNAME FROM #TempTableData)
  -->End  
  UNION ALL  
  -->Begin一个递归成员  
   SELECT #TempTableDetail.COUNTRYORDERID, #TempTableDetail.HSNAME, #TempTableDetail.COUNTRYNAME,#TempTableDetail.PARENTORDERID,
   #TempTableDetail.IMPORTCURRENTSUMAMOUNT,
   #TempTableDetail.IMPORTCONTRASTSUMAMOUNTPERCENTAGE,
   #TempTableDetail.IMPORTCURRENTSUMAMOUNTPERCENTAGE,
   CAST(REPLICATE(‘  ‘,LEN(CTE.TE))+#TempTableDetail.COUNTRYNAME AS NVARCHAR(MAX)) AS TE,Levle+1 AS Levle  
    FROM #TempTableDetail INNER JOIN CTE  
    ON #TempTableDetail.PARENTORDERID=CTE.COUNTRYORDERID  
    --group by #TempTableDetail.HSNAME
    WHERE #TempTableDetail.HSNAME IN (SELECT HSNAME FROM #TempTableData)
  -->End  
  )

  INSERT INTO #TempResult(COUNTRYORDERID,HSNAME,COUNTRYNAME,IMPORTCONTRASTSUMAMOUNTPERCENTAGE,IMPORTCURRENTSUMAMOUNTPERCENTAGE,IMPORTCURRENTSUMAMOUNT)
  SELECT DISTINCT COUNTRYORDERID, HSNAME,TE,IMPORTCONTRASTSUMAMOUNTPERCENTAGE,
   IMPORTCURRENTSUMAMOUNTPERCENTAGE,IMPORTCURRENTSUMAMOUNT FROM CTE ORDER BY HSNAME,COUNTRYORDERID;

效果:

技术分享

SQL 递归使用

标签:detail   mod   class   ica   begin   char   sum   select   where   

人气教程排行