USE [DB] GO /****** Object: View [dbo].[v_menus] Script Date: 02/24/2014 15:55:45 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER VIEW [dbo].[v_menus] AS WITH StepCTE AS ( SELECT guid, NodeCode, ParentNode, name, url, lcon, akState, aktype, num, 1 as Lev, ROW_NUMBER() OVER(ORDER BY (SELECT 1)) * 1000000 AS [seq] FROM ak_menus WHERE ParentNode='' ----or ParentNode is null UNION ALL SELECT T.guid, T.NodeCode, T.ParentNode, T.name, T.url, T.lcon, T.akState, T.aktype, T.num, CTE.Lev + 1, case when CTE.[Lev] = 1 then CTE.[seq] + ROW_NUMBER() OVER(ORDER BY (SELECT 1)) * 10000 --when CTE.[Lev] = 2 then CTE.[seq] + ROW_NUMBER() OVER(ORDER BY (SELECT 1)) * 100 --when CTE.[Lev] = 3 then CTE.[seq] + ROW_NUMBER() OVER(ORDER BY (SELECT 1)) else CTE.[seq] + ROW_NUMBER() OVER(ORDER BY (SELECT 1)) end as [seq] FROM ak_menus T INNER JOIN StepCTE CTE ON T.ParentNode = CTE.NodeCode ) SELECT guid, name,url,lcon,NodeCode,akState,aktype,num, Lev ,[seq] FROM StepCTE GO