WEB开发网
开发学院数据库MSSQL Server SQL2005/2008中的CTE应用--递归查询 阅读

SQL2005/2008中的CTE应用--递归查询

 2009-10-25 00:00:00 来源:WEB开发网   
核心提示: 这里举例说明如下:为了描述方便,邀月特地列举了一个常见的自关联Table表结构如下:表结构CREATETABLE[dbo].[CategorySelf]([PKID][int]IDENTITY(1,1)NOTNULL,[C_Name][nvarchar](50)NOTNULL,[C_Level]

这里举例说明如下:

为了描述方便,邀月特地列举了一个常见的自关联Table

表结构如下:

表结构

CREATE TABLE [dbo].[CategorySelf](
    [PKID] [int] IDENTITY(1,1) NOT NULL,
    [C_Name] [nvarchar](50) NOT NULL,
    [C_Level] [int] NOT NULL,
    [C_Code] [nvarchar](255) NULL,
    [C_Parent] [int] NOT NULL,
    [InsertTime] [datetime] NOT NULL,
    [InsertUser] [nvarchar](50) NULL,
    [UpdateTime] [datetime] NOT NULL,
    [UpdateUser] [nvarchar](50) NULL,
    [SortLevel] [int] NOT NULL,
    [CurrState] [smallint] NOT NULL,
    [F1] [int] NOT NULL,
    [F2] [nvarchar](255) NULL
 CONSTRAINT [PK_OBJECTCATEGORYSELF] PRIMARY KEY CLUSTERED 
(
    [PKID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

再插入一些测试数据

Insert
INSERT INTO [CategorySelf]([C_Name],[C_Level] ,[C_Code],[C_Parent] ,[InsertTime] ,[InsertUser] ,[UpdateTime]  ,[UpdateUser]  ,[SortLevel]  ,[CurrState]  ,[F1]  ,[F2])
select '分类1',1,'0',0,GETDATE(),'testUser',DATEADD(dd,1,getdate()),'CrackUser',13,0,1,'邀月备注' union all
select '分类2',1,'0',0,GETDATE(),'testUser',DATEADD(dd,78,getdate()),'CrackUser',12,0,1,'邀月备注' union all
select '分类3',1,'0',0,GETDATE(),'testUser',DATEADD(dd,6,getdate()),'CrackUser',10,0,1,'邀月备注' union all
select '分类4',2,'1',1,GETDATE(),'testUser',DATEADD(dd,75,getdate()),'CrackUser',19,0,1,'邀月备注' union all
select '分类5',2,'2',2,GETDATE(),'testUser',DATEADD(dd,3,getdate()),'CrackUser',17,0,1,'邀月备注' union all
select '分类6',3,'1/4',4,GETDATE(),'testUser',DATEADD(dd,4,getdate()),'CrackUser',16,0,1,'邀月备注' union all
select '分类7',3,'1/4',4,GETDATE(),'testUser',DATEADD(dd,5,getdate()),'CrackUser',4,0,1,'邀月备注' union all
select '分类8',3,'2/5',5,GETDATE(),'testUser',DATEADD(dd,6,getdate()),'CrackUser',3,0,1,'邀月备注' union all
select '分类9',4,'1/4/6',6,GETDATE(),'testUser',DATEADD(dd,7,getdate()),'CrackUser',5,0,1,'邀月备注' union all
select '分类10',4,'1/4/6',6,GETDATE(),'testUser',DATEADD(dd,7,getdate()),'CrackUser',63,0,1,'邀月备注' union all
select '分类11',4,'1/4/6',6,GETDATE(),'testUser',DATEADD(dd,8,getdate()),'CrackUser',83,0,1,'邀月备注' union all
select '分类12',4,'2/5/8',8,GETDATE(),'testUser',DATEADD(dd,10,getdate()),'CrackUser',3,0,1,'邀月备注' union all
select '分类13',4,'2/5/8',8,GETDATE(),'testUser',DATEADD(dd,15,getdate()),'CrackUser',1,0,1,'邀月备注' 

上一页  1 2 3 4  下一页

Tags:SQL CTE 应用

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接