自动越级查询
表结构如下
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)