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

求一动态SQL查询语句,高手们帮看看!
正在做后台添加模块.
MG_ID       MG_Name MG_Descript MG_ParentID
10000 系统设置 系统设置 0
10001 视学网后台管理 视学网后台管理 0
20001 教育书店管理 教育书店管理 10001
20002 讲师讲堂管理 讲师讲堂管理 10001
20003 九大频道管理 九大频道管理 10001
20004 播客管理 播客管理 10001
20005 论坛博客管理 论坛博客管理 10001
20006 博客管理 博客管理 10001
//根节点
select   max(MG_ID)   from   CE_MG_MenuPopedom   where   MG_ParentID=0
//二级节点
select   max(MG_ID)   from   CE_MG_MenuPopedom   where   MG_ParentID=10001
...这样是写死的
如何动态查找出每个节点下的最大的MG_ID

------解决方案--------------------
--??这样??

declare @MG_ID varchar(20),@MG_ParentID varchar(20)
set @MG_ParentID=??

exec sp_executesql
N 'select @MG_ID=max(MG_ID) from CE_MG_MenuPopedom where MG_ParentID=MG_ParentID ',
N '@MG_ID varchar(20) output, MG_ID@MG_ParentID varchar(20) ',
@MG_ID output,@MG_ParentID

select @MG_ID

------解决方案--------------------
--??这样??

select MG_ID=max(MG_ID) from CE_MG_MenuPopedom group by MG_ParentID
------解决方案--------------------
if exists(select 1 from sysobjects where name = '#temp ' and type= 'U ')
drop table #temp
create table #temp(MG_ParentID VARCHAR(50))
select MG_ParentID
insert #temp
from CE_MG_MenuPopedom
group by MG_ParentID

select max(MG_ID),MG_ParentID
from CE_MG_MenuPopedom A INNER JOIN #temp B
ON A.MG_ParentID=B.MG_ParentID
group by MG_ParentID

DROP TABLE #TEMP