数据表
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
CREATE TABLE
[dbo].[test] (
[Id] int IDENTITY(1, 1) NOT NULL,
[Name] nvarchar(50)
NULL,
[parenetId] int NULL,
[memo] text NULL)
ON
[PRIMARY]
TEXTIMAGE_ON [PRIMARY];
GO
数据库数据
需要实现的效果
这个结果其实是我一直想实现的,但是冥思苦想若干天都没有实现,最后放弃了。但是今天在一个群里,有个人提出了同样的需求,这正中我的想法,我又激情起来,这一次实现真的是出于巧合吧。没有多久我就想到了,不过也是借鉴了他人部分脚本,然后自己修改,最后得到想要的结果了。
数据脚本实现代码
SET QUOTED_IDENTIFIER ON;
GO
alter proc [dbo].[testxxxnew]
@id
int
as
begin
with SubQuery(ID,Name,parenetid,[Level]) as (
select ID,Name,parenetid,0 as [Level] from test where id=@id--isnull(parenetid
,0)= 0
union all
select A.ID,A.Name,A.parenetid,B.Level+1 AS
[Level]
from test A inner join SubQuery B
on A.parenetid = B.ID
)
select case [Level] when 0 then name else ‘‘ end as ‘第一级栏目‘ ,
case
[Level] when 1 then name else ‘‘ end as ‘第二级栏目‘ ,
case [Level] when 2 then
name else ‘‘ end as ‘第三级栏目‘
from SubQuery
end
GO
执行语句
exec testxxxnew 1
帮助他人其实也是在帮助自己。快乐学习!!