表结构: 1.item 实体表 itemID int PK 主键ID Number varchar 编码(多级01 01.01 01.01.01 ...有下级的做为目录,无下级的做为实体) parentID int FK(上级itemID,引用本表的itemID ) FDetail int (0为目录,1为实体)
select * from item where itemID=3 union all select * from item where FDetail=0 and parentID <(select parentID from item where itemID=3) and substring(Number,1,2) =(select substring(Number,1,2) from item where itemID=3) and substring(Number,4,2) =(select substring(Number,4,2) from item where itemID=3);
select * from (select a.*,b.qty from item a left join Inventory b on a.itemID=b.itemID)
start with itemID=1--从哪个ID开始
connect by prior itemID= parentID ;--父找子
-- select * from (select a.*,b.qty from item a left join Inventory b on a.itemID=b.itemID )
start with itemID=1--从哪个ID开始
connect by prior parentID = itemID;--子找父参考技术B@itemid--输入的变量(实体ID)
declare @taba TABLE([itemID] [int] NOT NULL,Number [varchar(100)] NOT NULL,parentID [int] NOT NULL,FDetail [int] NOT NULL) declare @pid int--父ID insert into @taba (itemID,Number,parentID,FDetail) select itemID,Number,parentID,FDetail from item where itemID=@itemid--取出当前行 select @pid=parentID where itemID=@itemid--取出当前行父ID while(exists(select top 1 * from item where itemID=@pid)) begin insert into @taba (itemID,Number,parentID,FDetail) select itemID,Number,parentID,FDetail from item where itemID=@pid--将父行插入 select @pid=parentID where itemID=@pid--再将父行的父ID插入,一直往上循环,直到查到没有父行为止 end ---手写的,可能有些错误,调试一下即可,这是变量表无限级循环,适合所有无限级分类表,更改一下也可以往下查无限级, ---哈哈,给分吧,70分哦,好多,以上各位的方法感觉是走入了死胡同 --变量表中的数据就是你要的数据参考技术C--查上级 with sub as( select itemID,Number,parentID from item where itemID=3 union all select a.itemID,a.Number,a.parentID from item a,sub b where a.itemID=b.parentID ) select * from sub
查下级 with sub as( select itemID,Number,parentID from item where itemID=3 union all select a.itemID,a.Number,a.parentID from item a,sub b where a.parentID=b.itemID ) select * from sub