Help me improve my query Help me improve this query. It took 8 minutes to generate 16k rows only.

SELECT TPG.group_id
INTO   #tempgroups
FROM   [sqlcdb-h05].[cosmocallv6].[dbo].tpersonnel AS TP
       INNER JOIN [sqlcdb-h05].[cosmocallv6].[dbo].tpersonnelprofile AS TPP
               ON TP.person_id = TPP.person_id
       INNER JOIN [sqlcdb-h05].[cosmocallv6].[dbo].tprofilegroups TPG
               ON TPP.profile_id = TPG.profile_id
WHERE  ( TP.person_id = 766 )
       AND ( TP.tenant_id = 112 ) 


SELECT DISTINCT AC.Agent_ID, AC.Group_ID, AC.GroupName
INTO #TempAgent
FROM [offlinedbsvr].[PLDTCustomerCare].[dbo].AgentConfiguration AC INNER JOIN
     #TempGroups ON AC.Group_ID = #TempGroups.Group_ID

DELETE FROM #TempAgent
WHERE NOT([dbo].[GetUpdatedAgentGroup](#TempAgent.Agent_ID) = #TempAgent.Group_ID)

-- End Grouping
BEGIN
    SELECT DISTINCT
        [Date] = CONVERT(VARCHAR(25), arrivaltime, 101),
        [Start Time] = arrivaltime,
        [End Time] = terminatedtime,
        [Duration] = DATEDIFF(ss, arrivaltime, terminatedtime),
        [Agent First Name] = co.agentfirstname,
        [Agent Last Name] = co.agentlastname,
        [Group Name] = groupname,
        [Phone Number Called] = outdialingaddress
    FROM
        [offlinedbsvr].[PLDTCustomerCare].[dbo].StreamSummary ss
            INNER JOIN [offlinedbsvr].[PLDTCustomerCare].[dbo].msgcallout co ON ss.call_id = co.call_id
            INNER JOIN #TempAgent ac ON co.agent_id = ac.agent_id
    WHERE
        arrivaltime BETWEEN '4/1/2014' AND '4/2/2014' AND
        ss.calldirection_id = 1
    ORDER BY
        [Date],
        [Group Name],
        [Agent Last Name],
        [Agent First Name],
        [Start Time],
        [End Time]


For the getUpdatedAgentGroup function, here's the code:

SELECT TOP 1 @AgentGroup = AC.Group_ID
FROM [offlinedbsvr].[PLDTCustomerCare].[dbo].AgentConfiguration AC
WHERE AC.Agent_ID = @AgentID
ORDER BY TIMESTAMP DESC
A very fast shot: do you need the sorting? Especially in your getUpdatedAgentGroup function? This may can be a quickfix. Another issue are indexes, have you them in place?