自动越级查询

poeily 2010-06-03 11:51:09
表结构如下
CREATE TABLE [dbo].[pub_dept] (
[dept_id] [int] NOT NULL ,
[dept_name] [varchar] (100) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[upparent] [int] NOT NULL ,
[orderindex] [int] NOT NULL ,
[Industry_id] [int] NULL ,
[IsLink] [bit] NULL ,
[remark] [varchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
[Dept_Subject_id] [varchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
[status] [int] NULL ,
[creator] [int] NOT NULL ,
[create_date] [datetime] NOT NULL ,
[modifier] [int] NULL ,
[modify_date] [datetime] NULL
) ON [PRIMARY]
GO

select dept_id from pub_dept where (dept_id in (select dept_id from pub_dept where dept_id in (select dept_id from pub_dept where upparent=2) or dept_id in (select dept_id from pub_dept where upparent in( select dept_id from pub_dept where upparent=2)) or dept_id in (select dept_id from pub_dept where upparent in (select dept_id from pub_dept where upparent in( select dept_id from pub_dept where upparent=2)))))

我这sql语句查出第二级id为2的下面的五级内的所有id,但是我想做出的效果是如果有第五级,就查出第五级,如果没有第五级的话就查出第4级,类推

if EXISTS(select dept_id from pub_dept where upparent in (select dept_id from pub_dept where upparent in( select dept_id from pub_dept where upparent=15)))

SELECT dept_id FROM pub_dept WHERE dept_id IN (select dept_id from pub_dept where upparent in (select dept_id from pub_dept where upparent in( select dept_id from pub_dept where upparent=15)))

ELSE IF EXISTS(SELECT dept_id FROM pub_dept WHERE dept_id in (select dept_id from pub_dept where upparent in( select dept_id from pub_dept where upparent=15)))

SELECT dept_id FROM pub_dept WHERE dept_id in (select dept_id from pub_dept where upparent in( select dept_id from pub_dept where upparent=15))

ELSE IF EXISTS(SELECT dept_id FROM pub_dept WHERE dept_id in (select dept_id from pub_dept where dept_id in (select dept_id from pub_dept where upparent=15)))

SELECT dept_id FROM pub_dept WHERE dept_id in (select dept_id from pub_dept where dept_id in (select dept_id from pub_dept where upparent=15))

这sql语句可以查出我要的部分效果,不过呢,因为最上面那机构下面可能有几个下级机构,可是我这sql语句只能查出下级的一个机构的id,

sql太乱了,兄弟们将就的看一下,帮我想想怎么写阿

ELSE

SELECT dept_id FROM pub_dept WHERE dept_id in (select dept_id from pub_dept where upparent=15)

...全文
98 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
yzf86211861 2010-06-03
  • 打赏
  • 举报
回复
顶下吧 太乱了眼睛花了
antiking 2010-06-03
  • 打赏
  • 举报
回复
参考这个。
http://topic.csdn.net/u/20100603/09/38aece21-cd57-4faf-9f49-cf3c611fa3ec.html
poeily 2010-06-03
  • 打赏
  • 举报
回复
还是看不懂你那个,我拷过来放数据库又报错,想看例子都看不了
antiking 2010-06-03
  • 打赏
  • 举报
回复
递归的。你加再多,都是递归下去的。
poeily 2010-06-03
  • 打赏
  • 举报
回复
稍微顶上一点
poeily 2010-06-03
  • 打赏
  • 举报
回复
2楼你那个我有点看不懂 你那是固定了机构吗?可是我那机构是动态的,是一个公司的部门,他随时都可能加多个机构,

62,071

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧