日期:2014-05-19  浏览次数:20643 次

求一存储过程****************
弄了二天了,实在没有头绪了,刚刚学习,很多地方不会!所以特来求助,!

是这样的,有一个省份表   (字典表_省)     其中字段为id   名称   所属   这三样!
里面的信息包括省,市,地区三级,省的所属为0   这个省的下级市的所属都为此省的id,嗯,每个市下面的区的所属即为市的id,举例如下

id           名称               所属
1             黑龙江省         0
2             哈尔滨市         1
3             大庆市             1
4             齐齐哈尔市     1
5             大同区             3
6             萨尔图区         3

就是这个意思!!!!
就是说黑龙江省下有哈市,大庆市,齐区,然后大庆市下面有大同区和萨尔图区,这样的!
我现在的要求是根据传来一个省的id,将省名,此省所属的全部市名和每个市名下面的区名全部调出来,即将此省下的所有地区都调出来!
哪位大大能帮帮忙,我现在是不知道怎么样去循环才好!


CREATE   PROCEDURE   pro
@proid   int,                     --传来的省id

AS
Declare   @strname   varchar(4000)         --定义变量
Declare   @strid       int         --定义变量
Declare   @str   nvarchar(4000)         --定义变量

BEGIN
       
          select   @strname=名称   from   字典表_省   where   id=   @proid     --调出此省的名称

          set   @str= '省名为 '+@strname+ '-- '          

          select   @strname=名称,   @strid=id   from   字典表_省   where   所属=   @proid
          --从这里开始即不知如何着手了,要如果查出此省下的每一个市,再根据每个市查出其下的所有区!!!!!!!不知如何循环了!
         
End

GO

如上,望高手大大们,帮个忙,感激不尽!

------解决方案--------------------
--function
create table T(id int,name varchar(30),pid int)
insert into T
select 1, '黑龍江省 ',0 union all
select 2, '哈爾冰市 ',1 union all
select 3, '大清 ',1 union all
select 4, '起迄哈兒 ',1 union all
select 5, '大同區 ',3 union all
select 6, '薩爾圖區 ',3

GO
Create function tree(@id int)
returns @t_level table(id int,level int)
AS
begin
declare @level int
set @level=0
insert into @t_level select @id,@level
while @@rowcount> 0
begin
set @level=@level+1
insert into @t_level select a.id,@level
from T a,@t_level b
where a.pid=b.id
and b.level=@level-1
end
return
end

GO

--id=3
select T.* from T , dbo.tree(3) A
where T.id=A.id
/*
id name pid
----------- ------------------------------ -----------
3 大清 1
5 大同區 3
6 薩爾圖區 3
*/

drop table T
drop function tree