62,254
社区成员
发帖
与我相关
我的任务
分享if object_id('tb') is not null drop table tb
create table tb
(
id char(6),
[name] varchar(20),
father char(6)
)
insert into tb select '001','教育收费','0'
union all select '002','课本','001'
union all select '003','大学课本','002'
;with hgo as
(
select * from tb where [name]=N'大学课本'
),
hgo1 as
(
select b.* from tb b,hgo h where b.id=h.father
),
hgo2 as
(
select b.* from tb b,hgo1 h where b.id=h.father
)
select * from hgo2
union all
select * from hgo1
union all
select * from hgo
id name father
------ -------------------- ------
001 教育收费 0
002 课本 001
003 大学课本 002
(3 行受影响)IF NOT OBJECT_ID('TB') IS NULL DROP TABLE TB
GO
CREATE TABLE TB([ID] NVARCHAR(3),[NAME] NVARCHAR(4),[FATHER] NVARCHAR(3))
Insert tb
SELECT N'001',N'教育收费',N'0' UNION ALL
SELECT N'002',N'课本',N'001' UNION ALL
SELECT N'003',N'大学课本',N'002' UNION ALL
SELECT N'004',N'劳而无功',N'0'
Go
SELECT * FROM TB
CREATE PROCEDURE P_TB_SEARCH
(@NAME VARCHAR(10))
AS
DECLARE @IDNO VARCHAR(10)
SELECT * INTO # FROM TB WHERE NAME=@NAME
SELECT @IDNO=FATHER FROM TB WHERE NAME=@NAME
WHILE @@ROWCOUNT>0
BEGIN
INSERT INTO # SELECT * FROM TB WHERE TB.ID=@IDNO
SELECT @IDNO=FATHER FROM TB WHERE ID=@IDNO
END
SELECT * FROM # ORDER BY ID
/*
ID NAME FATHER
---- ---- ------
001 教育收费 0
002 课本 001
003 大学课本 002
(所影响的行数为 3 行)
*/if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] varchar(3),[name] varchar(8),[father] varchar(3))
insert [tb]
select '001','教育收费','0' union all
select '002','课本','001' union all
select '003','大学课本','002' union all
select '004','××××','0'
go
with szx as
(
select * from tb where name='大学课本'
union all
select a.* from tb a join szx b on a.id=b.father
)
select * from szx order by id
--测试结果:
/*
id name father
---- -------- ------
001 教育收费 0
002 课本 001
003 大学课本 002
(3 行受影响)
*/
select * from yourtable t1 where t1.name = '大学课本'
union select * from yourtable t2 where t2.id in (select father from yourtable where name = '大学课本')
union select * from yourtable t3 where t3.ID in(select father from yourtable t2 where t2.id in (select father from yourtable where name = '大学课本'))