我发现以下查询在生产环境中运行,这需要很长时间才能执行。有没有办法优化这个逗号分隔值查询?
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
答案 0 :(得分:1)
尝试此备用
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)