樹形表結構以下express
IF EXISTS (SELECT * FROM sys.all_objects WHERE object_id = OBJECT_ID(N'[dbo].[Test]') AND type IN ('U')) DROP TABLE [dbo].[Test] GO CREATE TABLE [dbo].[Test] ( [Id] bigint IDENTITY(1,1) NOT NULL, [TypeName] nvarchar(50) COLLATE Chinese_PRC_CI_AS NOT NULL, [ParentId] bigint NULL ) GO -- ---------------------------- -- Records of Test -- ---------------------------- SET IDENTITY_INSERT [dbo].[Test] ON GO INSERT INTO [dbo].[Test] ([Id], [TypeName], [ParentId]) VALUES (N'1', N'生活常識', N'0') GO INSERT INTO [dbo].[Test] ([Id], [TypeName], [ParentId]) VALUES (N'2', N'生活', N'1') GO INSERT INTO [dbo].[Test] ([Id], [TypeName], [ParentId]) VALUES (N'3', N'常識', N'2') GO SET IDENTITY_INSERT [dbo].[Test] OFF GO
須要實現的結果ide
對於這種狀況有三種解決方案:遊標、循環、CTEspa
DECLARE @temp nvarchar(MAX)='',@pid bigint=3; WHILE @pid<>0 BEGIN IF @temp='' SELECT @temp=TypeName,@pid=ParentId FROM [dbo].[Test] WHERE Id=@pid; ELSE SELECT @temp=(TypeName+'->'+@temp),@pid=ParentId FROM [dbo].[Test] WHERE Id=@pid; END; SELECT @temp AS TypeName;
;with Tree as ( select * from [Test] where Id=3 union all select a.* from [Test] a join Tree b on a.Id=b.ParentId ) select stuff((select '->' + TypeName from Tree order by Id FOR XML PATH('')),1,5,'')
CTE語法.net
;[ WITH [ ,n ] ] ::= expression_name [ ( column_name [ ,n ] ) ] AS ( CTE_query_definition )
在使用CTE時應注意以下幾點:
一、CTE後面必須直接跟使用CTE的SQL語句(如select、insert、update等),不然,CTE將失效。code
二、CTE後面也能夠跟其餘的CTE,但只能使用一個with,多個CTE中間用逗號(,)分隔,以下blog
;with cte1 as ( select * from table1 where name like 'abc%' ), cte2 as ( select * from table2 where id > 20 ), cte3 as ( select * from table3 where price < 100 ) select a.* from cte1 a, cte2 b, cte3 c where a.id = b.id and a.id = c.id
三、若是CTE的表達式名稱與某個數據表或視圖重名,則緊跟在該CTE後面的SQL語句使用的仍然是CTE,固然,後面的SQL語句使用的就是數據表或視圖了,以下get
-- table1是一個實際存在的表 ;with table1 as ( select * from persons where age < 30 ) select * from table1 -- 使用了名爲table1的公共表表達式 select * from table1 -- 使用了名爲table1的數據表
四、CTE 能夠引用自身,也能夠引用在同一 WITH 子句中預先定義的 CTE。不容許前向引用。it
五、不能在 CTE_query_definition 中使用如下子句:
(1)COMPUTE 或 COMPUTE BY
(2)ORDER BY(除非指定了 TOP 子句)
(3)INTO
(4)帶有查詢提示的 OPTION 子句
(5)FOR XML
(6)FOR BROWSEio
六、若是將 CTE 用在屬於批處理的一部分的語句中,那麼在它以前的語句必須以分號結尾,event