I'm trying to optimize or completely rewrite this query. It takes about ~1500ms to run currently. I know the distinct's are fairly inefficient as well as the Union. But I'm struggling to figure out exactly where to go from here.
I am thinking that the first select statement might not be needed to return the output of;
[Key | User_ID,(User_ID)]
Note; Program and Program Scenario are both using Clustered Indexes. I can provide a screenshot of the Execution Plan if needed.
ALTER FUNCTION [dbo].[Fn_Get_Del_User_ID] (@_CompKey INT)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @UseID AS VARCHAR(8000);
SET @UseID = '';
SELECT @UseID = @UseID + ', ' + x.User_ID
FROM
(SELECT DISTINCT (UPPER(p.User_ID)) as User_ID FROM [dbo].[Program] AS p WITH (NOLOCK)
WHERE p.CompKey = @_CompKey
UNION
SELECT DISTINCT (UPPER(ps.User_ID)) as User_ID FROM [dbo].[Program] AS p WITH (NOLOCK)
LEFT OUTER JOIN [dbo].[Program_Scenario] AS ps WITH (NOLOCK) ON p.ProgKey = ps.ProgKey
WHERE p.CompKey = @_CompKey
AND ps.User_ID IS NOT NULL) x
RETURN Substring(@UserIDs, 3, 8000);
END
UNIONthere is no need to selectDISTINCTas well. The de-duplication ofUNIONworks on the entire unioned set. You should probably also need anINNER JOINrather than aLEFT JOIN. WithAND ps.User_ID IS NOT NULLit already is an inner join. (This won't help performance though)