
这个问题的存储过程怎么写,郁闷死了
user_table 表(user_id,userName)
user_group_table表(ug_id,user_id,group_id)
group_table表(group_id,group_name,parent_id)
user_table:
1,张三
2,李四
user_group_table:
1,1,3
2,1,4,
3,2,5
group_table:
1,1组,0
2,2组,0
3,1.1组,1
4,2,1组,2
5,3组,0
用存储过程查询得到一下样式的数据
张三,1组/1,1组&2组/2.1组
李四,3组
请问这个存储过程怎么写?或者是思路是什么?(数据库sqlserver 2008) 展开
--插入测试数据
select * into user_table from (
select 1 as user_id,'张三' as userName union all
select 2,'李四' )a
select * into user_group_table from (
select 1 as ug_id,1 as user_id,3 as group_id union all
select 2,1,4 union all
select 3,2,5)a
select * into group_table from (
select 1 as group_id,'1组' as group_name,0 as parent_id union all
select 2,'2组',0 union all
select 3,'1.1组',1 union all
select 4,'2.1组',2 union all
select 5,'3组',0)a
--推荐使用视图:
--需要用到视图1,代码如下:
create view v_user_Group_Data as
select cc.user_id,cc.userName,aa.group_id,aa.group_name,aa.parent_id
from group_table aa
left join user_group_table bb
on aa.group_id =bb.group_id
left join user_table cc
on bb.user_id=cc.user_id
go
--需要用到视图2,代码如下:
create view v_all_data as
with usdata(group_id,group_name,parent_id,new_gourp_name,userName) as
(
select group_id,group_name,parent_id, CAST(group_name as VARCHAR(8000))
as new_gourp_name,userName from v_user_Group_Data
where parent_id=0
union all
select b.group_id,b.group_name,b.parent_id,
(CASE when b.parent_id=0 then new_gourp_name
else new_gourp_name+'/'+b.group_name
end),b.userName
from usdata a
inner join v_user_Group_Data b
on a.group_id=b.parent_id
)
select userName, new_gourp_name=replace(stuff
(
(select '&'+new_gourp_name
from usdata a where a.userName=b.userName for xml path('')
),1,1,''
) ,'amp;','')
from usdata b where userName is not null group by userName
go
--测试查询
select * from user_table
select * from user_group_table
select * from group_table
go
--执行查询:
select * from v_all_data
--视图可以附带条件:
select * from v_all_data where userName='张三'
结果如下:
user_id userName
----------- --------
1 张三
2 李四
(2 行受影响)
ug_id user_id group_id
----------- ----------- -----------
1 1 3
2 1 4
3 2 5
(3 行受影响)
group_id group_name parent_id
----------- ---------- -----------
1 1组 0
2 2组 0
3 1.1组 1
4 2.1组 2
5 3组 0
(5 行受影响)
userName new_gourp_name
-------- --------------------
李四 3组
张三 2组/2.1组&1组/1.1组
(2 行受影响)
userName new_gourp_name
-------- ----------------------------
张三 2组/2.1组&1组/1.1组
(1 行受影响)
--安徽康磊科技 工程师为您解答

2025-08-11 广告