SQLserver資料庫中關於遞迴的查詢使用

2021-07-06 00:20:09 字數 1213 閱讀 5528

度量快速開發平台資料庫支援sqlserver資料庫,我們之前習慣的oracle遞迴查詢用的 start with dept_id=1000 connect by prior dept_id=upper_id的方式就不靈了。

比如我們的組織機構裡面有很多下級機構及部門,要查詢出登入人所在的機構,並列出該機構下所有機構和部門。sqlserver寫法如下:

with newtable as

(select a.dept_id,a.dept_name,a.upper_id,a.tree_code,a.extend_type,a.dept_level,a.sort_order from sa_dept_dict a where a.dept_id=登入使用者的部門id

union all

select b.dept_id,b.dept_name,b.upper_id,b.tree_code,b.extend_type,b.dept_level,b.sort_order from sa_dept_dict b inner join newtable c on b.dept_id=c.upper_id

where b.dept_type=2 or b.dept_type=6) ,

newtable1 as

(select a.dept_id,a.dept_name,a.upper_id,a.tree_code,a.extend_type,a.dept_level,a.sort_order from sa_dept_dict a , (select right(max(tree_code),4) dept_id from newtable where extend_type='機構' ) c where a.dept_id=c.dept_id

union all

select b.dept_id,b.dept_name,b.upper_id,b.tree_code,b.extend_type,b.dept_level,b.sort_order from sa_dept_dict b inner join newtable1 c on c.dept_id=b.upper_id

where b.dept_type=2 or b.dept_type=6

) select dept_id,dept_name,upper_id,sort_order,extend_type,tree_code from newtable1

撰寫人:度量科技www.delit.cn

關於 SQL Server 資料庫

表 包含資料庫中所有資料的資料庫物件,由行和列組成,用於組織和儲存資料。字段 表中的列稱為乙個字段,字段具有自己的屬性,如欄位型別 字段大小等。基本字段型別 字元型 文字型 數值型 邏輯型 日期時間型。索引 單獨的 物理的資料庫結構,依賴於表建立,使資料庫程式無須對整個表進行掃瞄,就可以找到所需資料...

關於SQLserver資料庫的備份

資料庫備份一直是乙個很重要的工作,當資料庫崩潰以後進行恢復它就是乙個很重要的東西。今天我說一下自己在實際是怎麼運用的,各位大蝦可以跳過。首先,要完成進行乙個 硬碟的備份。也就是傳說中的 雙機熱備。我不擅長這個東西,這個是公司的系統管理員做的。他給我解釋的原理就是,多塊硬碟的備份,在對一塊硬碟進行操作...

關於SqlServer資料庫日期函式

關於sqlserver資料庫日期函式 1 獲取當前時間 select getdate 2 擷取需要的值 select datepart year,getdate select datepart month,getdate select datepart day,getdate select date...