需要有关sql循环查询的帮助
我的表:
我期待的输出:
我只能获得1行..
declare @ID nvarchar(50) = (select EMP_ID from HRS_WORKFLOW01);
CREATE TABLE #TEMP(EMP_ID NVARCHAR(200),EMP_L1 NVARCHAR(200),EMP_L2 NVARCHAR(200),EMP_L3 NVARCHAR(200),EMP_L4 NVARCHAR(200))
DECLARE @L1 NVARCHAR(50);
DECLARE @L2 NVARCHAR(50);
DECLARE @L3 NVARCHAR(50);
DECLARE @L4 NVARCHAR(50);
SET @L1 = (SELECT L1EmplNo FROM HRS_WORKFLOW01 WHERE EMP_ID =@ID)
INSERT INTO #TEMP (EMP_ID,EMP_L1)VALUES(@ID,@L1)
SET @L2 = (SELECT L1EmplNo FROM HRS_WORKFLOW01 WHERE EMP_ID =@L1)
UPDATE #TEMP SET EMP_L2=@L2 WHERE EMP_ID=@ID
SET @L3 = (SELECT L1EmplNo FROM HRS_WORKFLOW01 WHERE EMP_ID =@L2)
UPDATE #TEMP SET EMP_L3=@L3 WHERE EMP_ID=@ID
SET @L4 = (SELECT L1EmplNo FROM HRS_WORKFLOW01 WHERE EMP_ID =@L3)
UPDATE #TEMP SET EMP_L4=@L4 WHERE EMP_ID=@ID
SELECT * FROM #TEMP
答案 0 :(得分:3)
您需要使用Recursive CTE
;WITH DATA
AS (SELECT *
FROM (VALUES ('ALI','ABU'),
('JOSH','LIM'),
('JAMES','KAREN'),
('LIM','JERRY'),
('JERRY','GEM')) TC(EMP_ID, EMP_L1)),
REC_CTE
AS (SELECT EMP_ID,
EMP_L1,
Cast(EMP_L1 AS VARCHAR(8000)) AS PARENT,
LEVEL = 1
FROM DATA
UNION ALL
SELECT D.EMP_ID,
D.EMP_L1,
Cast(RC.PARENT + '.' + D.EMP_L1 AS VARCHAR(8000)),
LEVEL = LEVEL + 1
FROM DATA D
JOIN REC_CTE RC
ON RC.EMP_ID = D.EMP_L1)
SELECT TOP 1 WITH TIES EMP_ID,
EMP_L1 = COALESCE(Parsename(PARENT, 1), ''),
EMP_L2 = COALESCE(Parsename(PARENT, 2), ''),
EMP_L3 = COALESCE(Parsename(PARENT, 3), ''),
EMP_L4 = COALESCE(Parsename(PARENT, 4), '')
FROM REC_CTE
ORDER BY Row_number()OVER(PARTITION BY EMP_ID ORDER BY LEVEL DESC)
OPTION (MAXRECURSION 0)
结果:
╔════════╦════════╦════════╦════════╦════════╗
║ EMP_ID ║ EMP_L1 ║ EMP_L2 ║ EMP_L3 ║ EMP_L4 ║
╠════════╬════════╬════════╬════════╬════════╣
║ ALI ║ ABU ║ ║ ║ ║
║ JAMES ║ KAREN ║ ║ ║ ║
║ JERRY ║ GEM ║ ║ ║ ║
║ JOSH ║ LIM ║ JERRY ║ GEM ║ ║
║ LIM ║ JERRY ║ GEM ║ ║ ║
╚════════╩════════╩════════╩════════╩════════╝
注意:这认为最多可以有4个级别。为了将数据拆分成不同的列,我使用了PARSENAME
函数,如果超过4个级别,这将无效。
如果您不想将父母分成不同的列,请移除PARSENAME
并单独选择PARENT
列。