I am using SQL Server 2008 and am trying to run:
WITH results (Row, code, p_name, phone, intake_date, shipped_status, shipped_date,
event_status, intake_status, slsperson, referral_source, dr )
AS
(
SELECT ROW_NUMBER() OVER (ORDER BY intake_date ASC)AS Row, code, p_name, phone,
intake_date, shipped_status, shipped_date, event_status, intake_status, slsperson,
referral_source, dr
FROM db.schema.sales_referral_list('2012-05-1', '2012-06-1', 'CXJ7')
)
SELECT Row, code as p_id, p_name, phone, intake_status, intake_date, shipped_status,
shipped_date, event_status, slsperson, referral_source, dr
FROM results
WHERE Row BETWEEN 0 AND 50 ORDER BY Row
When I run it without the With AS statement (i.e. just the inner select statement), it executes in about 1 second. When I use the With statement, that I use for pagination on the site, it takes over 15 sec to execute. Is there some optimization I can do to increase the performance on this statement? (sales_referral_list is a table value function that takes 3 parameters. It runs in under 1 sec all the time, so I am relatively sure it is not the problem). Thanks for any help you can give.
==========UPDATE=========
The table value function is as follows: The table value function is as follows:
(
-- Add the parameters for the function here
@START DATE,
@END DATE,
@SLSCODE VARCHAR(4)
)
RETURNS TABLE
AS
RETURN
(
-- Add the SELECT statement with parameter references here
SELECT
A.code,
B.last+', '+B.first AS p_name,
B.phoneday AS Phone,
B.slcode,
B.regdate as intake_date,
CASE
WHEN CAST(C.newdate AS DATE) is not null THEN 'SHIPPED'
WHEN B.udef1='03' THEN 'NON-SERV'
ELSE 'NOT SHIPPED'
END as shipped_status,
CASE
WHEN CAST(C.newdate AS DATE)='1900-01-01' THEN ''
ELSE CAST(C.newdate AS DATE)
END as shipped_date,
CASE
WHEN E.status='1' THEN 'ACTIVE'
WHEN E.status='2' THEN 'COMPLETE'
WHEN E.status='0' THEN 'DELETED'
ELSE 'NO EVENT'
END event_status,
F.file_status as intake_status,
D.employee as slsperson,
B.rfname as referral_source,
B.dcname as doctor
FROM event.dbo.distinct_account() a
LEFT OUTER JOIN event.dbo.patient_dg() B ON A.code=B.code
LEFT OUTER JOIN event.dbo.newdate() c on a.code=c.ACCOUNT
LEFT OUTER JOIN event.dbo.employee D ON B.slname=D.employee
LEFT OUTER JOIN(
SELECT
id,
patient_id,
status
FROM event.dbo.event A
WHERE A.task_id IN ('WF','WT')
group by id,patient_id,status
) E ON A.code=E.patient_id
LEFT OUTER JOIN event.dbo.taskWF F ON E.id=F.event_id
WHERE b.regdate>=@START
AND b.regdate<=@END
AND slcode=@SLSCODE
)
Normal returned results are somewhere between 100 - 500 records. Table Value Function patient_dg has approximately 60,000 records