I have found the below query running within the production environment which is taking a long time to execute. Is there any way to optimize this comma separated value query?
SELECT
EmpID, EmployeeName, DeptID, HomeAddress, EmailId,
STUFF( (SELECT DISTINCT '@!#' + CT.Country_Name CT
INNER JOIN Employee_Country EA ON CT.Country_Id = EA.Country_Id
WHERE E.EmpID = EA.EmpID AND EA.Active = 1 FOR XML PATH('')), 1, 3, '') as 'Country',
STUFF( (SELECT DISTINCT '@!#' + CT.CityName CT
INNER JOIN Employee_City EA ON CT.City_Id = EA.City_Id
WHERE E.EmpID = EA.EmpID AND EA.Active = 1 FOR XML PATH('')), 1, 3, '') as 'City',
STUFF( (SELECT DISTINCT '@!#' + CT.Number CT
INNER JOIN Employee_PhonNumbers EA ON CT.PNumberId = EA.PNumberId
WHERE E.EmpID = EA.EmpID AND EA.Active = 1 FOR XML PATH('')), 1, 3, '') as 'PhoneNumber',
------so on------
FROM Employee E
WHERE Active = 1
Try this alternate
SELECT EmpID,
EmployeeName,
DeptID,
HomeAddress,
EmailId,
Country_Name= LEFT(Country_Name, Len(Country_Name) - 1),
CityName= LEFT(CityName, Len(CityName) - 1),
Number= LEFT(Number, Len(Number) - 1)
FROM Employee E
OUTER APPLY (SELECT DISTINCT '@!#' + CT.Country_Name
FROM country CT
INNER JOIN Employee_Country EA
ON CT.Country_Id = EA.Country_Id
WHERE E.EmpID = EA.EmpID
AND EA.Active = 1
FOR XML PATH('')) Country (Country_Name)
OUTER APPLY (SELECT DISTINCT '@!#' + CT.CityName
FROM City CT
INNER JOIN Employee_City EA
ON CT.City_Id = EA.City_Id
WHERE E.EmpID = EA.EmpID
AND EA.Active = 1
FOR XML PATH('')) City (CityName)
OUTER APPLY (SELECT DISTINCT '@!#' + CT.Number
FROM PhonNumbers CT
INNER JOIN Employee_PhonNumbers EA
ON CT.PNumberId = EA.PNumberId
WHERE E.EmpID = EA.EmpID
AND EA.Active = 1
FOR XML PATH('')) PhonNumbers (Number)
GROUP BY Name,
EmployeeName,
DeptID,
HomeAddress,
EmailId,
LEFT(Country_Name, Len(Country_Name) - 1),
LEFT(CityName, Len(CityName) - 1),
LEFT(Number, Len(Number) - 1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.