Monday, 16 May 2016

Sql nest CTE properly

 --First CTE
;with CTE as (
select  
 C.Id,C.App_DepartmentCode,C.SenttoLevelCD ,C.ComplaintCode,D.DepartmentName_U,
 (Case When isnull(D.parentdepartment,'0') ='0' Then C.App_DepartmentCode
 when isnull(D.parentdepartment,'0')<>'0' 
Then D.parentdepartment end) As parent
 from tbl_Complaints_CompiledStatus C inner join tbl_Department D On
 D.DepartmentCode=C.App_DepartmentCode
 and  C.IsFirstForwording='Yes' and  C.CompType=1 
 and C.ComplaintCount=1 and C.IsFinalStatus_FirstLevel='ATRS'
 and C.App_DepartmentCode  <> 0
 ),
 
--- Second CTE

  CTE1 as(
 select  CTE.id,App_DepartmentCode,SenttoLevelCD,ComplaintCode,
CTE.DepartmentName_U,ISNULL(ORD.Userid,0) Userid
,username,parent from CTE
 inner join tbl_Department D ON CTE.parent=D.departmentcode
  left join tbl_orderby ORD ON ORD.Userid=D.ParbhariAdhikariCD
   where ORD.Userid <> 0
 
   )
--UPDATE USING ABOVE CTE

 UPDATE A   
  SET A.ParbhariAdhikari = B.username,   A.ParbhariAdhikariCD = B.userid,
   A.Parentdepartment=B.parent from tbl_Complaints_CompiledStatus  A
  INNER JOIN CTE1  B
    ON A.ID = B.ID

No comments:

Post a Comment

Table Partitioning in SQL Server

  Table Partitioning in SQL Server – Step by Step Partitioning in SQL Server task is divided into four steps: Create a File Group Add Files ...