日期:2014-05-18  浏览次数:20575 次

求助一个生成树形目录的SQL语句或者过程
求助一个生成树形目录的SQL语句或者过程
现有表的结构是如此 prodsname,prodname
  女戒,钻石女戒
  女戒,豪华女戒
  男戒,钻石男戒
  男戒,豪华男戒
  男戒,特殊男戒
  吊坠,钻石吊坠

要求生成一个表ID,FATHERID,PRODNAME
  1,0,女戒
  2,0,男戒
  3,0,吊坠
  4,1,钻石女戒
  5,1,豪华女戒
  6,2,钻石男戒
  7,2,豪华男戒
  8,2,特殊男戒
  9,3,钻石吊坠


------解决方案--------------------
SQL code

create table #t (id int identity(1,1) ,pid int, v varchar(10))
go

declare @t table(v1 varchar(10),v2 varchar(10));
insert into @t select '女戒','钻石女戒' union all
select '女戒','豪华女戒' union all
select '男戒','钻石男戒';

select * from @t;

insert into #t (pid,v) select 0,v1 from (select distinct v1 from @t) x;

insert into #t (pid,v) select a.id,b.v2 from #t a join @t b on b.v2 like '%'+a.v


select * from #t;

drop table #t;

/*
id          pid         v
----------- ----------- ----------
1           0           男戒
2           0           女戒
3           1           钻石男戒
4           2           钻石女戒
5           2           豪华女戒
*/

------解决方案--------------------
SQL code
create table tb(prodsname nvarchar(10),prodname nvarchar(10))
insert into tb select '女戒','钻石女戒'
insert into tb select '女戒','豪华女戒'
insert into tb select '男戒','钻石男戒'
insert into tb select '男戒','豪华男戒'
insert into tb select '男戒','特殊男戒'
insert into tb select '吊坠','钻石吊坠'
go
select row_number()over(order by (select 1))id,* into # from (select distinct 0 as pid,prodsname from tb)t
insert into #
select row_number()over(order by(select 1))+(select max(id) from #),a.id,b.prodname from # a inner join tb b on a.prodsname=b.prodsname
select * from # order by id
/*
id                   pid         prodsname
-------------------- ----------- ----------
1                    0           吊坠
2                    0           男戒
3                    0           女戒
4                    1           钻石吊坠
5                    2           钻石男戒
6                    2           豪华男戒
7                    2           特殊男戒
8                    3           钻石女戒
9                    3           豪华女戒

(9 行受影响)

*/
go
drop table tb,#