This is my query:
SELECT
wp.WorkplanID,
STUFF((SELECT ', ' + ISNULL(ul.FirstName + ' ', '') + ISNULL(ul.LastName, '')
FROM UserLogin ul
INNER JOIN Vendors v ON ul.UserLoginID = v.UserLoginID
INNER JOIN dbo.WorkPlanVendors wpv ON wpv.VendorID = CAST(v.VendorID AS INT)
WHERE wpv.WorkPlanID = wp.WorkPlanID
FOR XML PATH('')), 1, 2, '') AS VendorName,
STUFF((SELECT ', ' + v.PrimaryPhone
FROM UserLogin ul
INNER JOIN Vendors v ON ul.UserLoginID = v.UserLoginID
INNER JOIN dbo.WorkPlanVendors wpv ON wpv.VendorID = CAST(v.VendorID AS INT)
WHERE wpv.WorkPlanID = wp.WorkPlanID
FOR XML PATH('')), 1, 2, '') AS PrimaryPhone,
STUFF((SELECT ', ' + ul.Email
FROM UserLogin ul
INNER JOIN Vendors v ON ul.UserLoginID = v.UserLoginID
INNER JOIN dbo.WorkPlanVendors wpv ON wpv.VendorID = CAST(v.VendorID AS INT)
WHERE wpv.WorkPlanID = wp.WorkPlanID
FOR XML PATH('')), 1, 2, '') AS Email
FROM WorkPlan wp
It is taking 5 seconds to get data but I want to make it faster.
3条答案
按热度按时间vmpqdwk31#
You used the same query for three columns. You can use a common table expression to join the tables once and use this reference in your query as below:
f0ofjuux2#
The existing answers do not help as they all query the base table many times.
You can use the following solution to query the base table once and aggregate it up:
In an
APPLY
, useFOR XML PATH('row')
to aggregate up the entire dataset into one XML. Add in the commas.In the
SELECT
, query each column as follows:.query('row/TheColumn/text()')
this gets you all the text elements for that name..value('text()[1]', 'nvarchar(max)')
this unescapes any XML encoding.Use
STUFF
to strip off the leading comma.Obviously in newer versions of SQL Server you don't need any of this, you can just use
STRING_AGG
.tzcvj98z3#