存储过程循环错误

时间:2016-09-07 02:30:23

标签: sql sql-server

我是存储过程的新手,我收到错误:

  

子查询返回的值超过1。当子查询跟随

时,不允许这样做

My Table

E_R_Main是标头表,E_R_Detail是详细信息表。两个表都使用R_ID连接。

我的预期输出:

enter image description here

代码:

DECLARE @LALA  NVARCHAR(10);
DECLARE @LALA2  NVARCHAR(10);

CREATE TABLE #TEMP 
(
    EMP_NAME nvarchar(256), 
    Total_Pending nvarchar(256),
    Reschedule_Task nvarchar(256),
    New_Task nvarchar(256)
)

--select * from #TEMP

INSERT INTO #TEMP(EMP_NAME, Total_Pending) 
    SELECT DISTINCT(PIC), COUNT(PIC) AS COUNTTT 
    FROM E_R_DetailT A
    INNER JOIN E_R_MainT b ON a.R_ID = b.R_ID
    WHERE PIC IS NOT NULL 
    GROUP BY T_EMP_ID 

SET @LALA = (SELECT COUNT(B.R_ID) AS TEXSST 
             FROM E_R_MainT A 
             INNER JOIN E_R_DetailT B ON A.R_ID = B.R_ID 
             WHERE (b.R_Y = '[Redo]' OR R_Y_N = '[r]') 
               AND (STAT = 'S_5' OR STAT = 'S_3') 
             GROUP BY T_EMP_ID )

SET @LALA2 = (SELECT DISTINCT(B.T_EMP_ID) 
              FROM E_R_MainT A 
              INNER JOIN E_R_DetailT B ON A.R_ID = B.R_ID 
              WHERE (b.R_Y = '[Redo]' OR R_Y_N = '[r]') 
                AND (STAT = 'S_5' OR STAT = 'S_3')  
              GROUP BY T_EMP_ID)

UPDATE #TEMP 
SET Reschedule_Task = @LALA 
WHERE #TEMP.EMP_NAME = @LALA2

--SELECT * FROM #TEMP
SELECT 
    B.Name, a.Total_Pending, New_Task,
    CASE 
       WHEN Reschedule_Task IS NULL
          THEN 0 
          ELSE Reschedule_Task 
    END AS User_Feedback 
FROM 
    #TEMP A
INNER JOIN 
    UserInfo B ON A.EMP_NAME = B.EmployeeNo

DROP TABLE #TEMP

1 个答案:

答案 0 :(得分:2)

您的代码似乎比解决此问题所需的代码更复杂。它看起来像带有条件聚合的JOIN

select d.pic, 
       sum(case when m.status in ('S_1', 'S_3', 'S_4') then 1 else 0 end) as Pending,
       sum(case when m.status = 'S_1' then 1 else 0 end) as New,
       sum(case when m.status = 'S_3' then 1 else 0 end) as Reschedule,
       sum(case when m.status = 'S_4' then 1 else 0 end) as Completed
from e_r_main m join
     e_r_detail d
     on m.r_id = d.r_id
group by d.pic;