WITH AS 語句在部門層級關係中的應用

CREATE TABLE DEPT
(
  DEPT_ID NVARCHAR(20) NOT NULL PRIMARY KEY
  ,DEPT_NAME NVARCHAR(40)
  ,PARENT_ID NVARCHAR(20)
  )
GO

INSERT INTO DEPT(DEPT_ID,DEPT_NAME,PARENT_ID)
SELECT '10','工廠A','' UNION ALL
SELECT '11','車間A','10' UNION ALL
SELECT '12','車間B','10' UNION ALL
SELECT '13','生產線1','11' UNION ALL
SELECT '14','生產線2','11' UNION ALL
SELECT '15','生產線3','11' UNION ALL
SELECT '16','工序1組','13' UNION ALL
SELECT '17','工序2組','13'

--(1)查詢指定部門的上級部門
DECLARE @dept_id NVARCHAR(20)
SET @dept_id='13';
WITH w_dept AS (
  SELECT d.* FROM   dbo.DEPT d WHERE  d.DEPT_ID = @dept_id
  UNION ALL
  SELECT d.*  FROM   dbo.DEPT d INNER JOIN w_dept ON d.dept_id = w_dept.PARENT_ID
  )
SELECT * FROM w_dept ORDER BY DEPT_ID
/* 
  延伸應用:
  在部門表DEPT中增長層級LEVEL,就能夠定位到某個層級的部門,好比找出當前部門的二級父部門
  SELECT * FROM w_dept WHERE LEVEL=2 
 */

--(2)查詢指定部門的下屬部門
DECLARE @dept_id NVARCHAR(20)
SET @dept_id='13';
WITH w_dept AS (
  SELECT d.* FROM   dbo.DEPT d WHERE  d.DEPT_ID = @dept_id
  UNION ALL
  SELECT  d.*  FROM   dbo.DEPT d INNER JOIN w_dept ON d.PARENT_ID = w_dept.DEPT_ID
  )
SELECT * FROM w_dept ORDER BY DEPT_ID 

/* 
  延伸應用:
  把部門編號串成一個字符串,而後查詢當前部門及下屬部門全部員工
  DECLARE @TEMPS NVARCHAR(MAX)
  SELECT @TEMPS=ISNULL(@TEMPS,'') + RTRIM(DEPT_ID) +'|' FROM w_dept
  SELECT @TEMPS
  SELECT * FROM EMP WHERE CHARINDEX(RTRIM(DEPT_ID)+'|',@TEMPS)>0
 */

 

官網文檔參考:sql

WITH common_table_expression (Transact-SQL)express

https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sqlspa

相關文章
相關標籤/搜索