Link to home
Start Free TrialLog in
Avatar of Dale Fye
Dale FyeFlag for United States of America

asked on

CTE's only valid for a single operation? Are there alternatives?

I'm have been performing a MERGE operation to push data from a production database into a reporting database on a daily basis (05:00AM) but this process has recently started taking well over an hour.  I posted here the other day about this and the response was that I should consider performing a delete and corresponding append rather than using the MERGE with If Found and If not Found operation.

I wrote an SP which looks something like the following (where "FieldList" is actually a list of fields).

;WITH Recent_Production (FieldList)
AS 
(
SELECT FieldList
FROM ProductionTable
)

DELETE FROM tbl_Reports
WHERE Exists (SELECT 1 FROM Recent_Production  
WHERE Entity_ID = tbl_Reports.Entity_ID AND ProductionDate = tbl_Reports.docDate)

INSERT INTO tbl_Reports
SELECT * FROM Recent_Production

Open in new window

But this does not work, because the CTE is not found in the second operation (INSERT command).  I've never used CTE's before, but I was under the impression that one of the reasons for using CTEs was to eliminate the need to define a recordset more than once in a procedure.   I've recently discovered that the CTE is only valid for the first operation after it is defined, which is why it works for either the DELETE or the INSERT, when I remark out the other one, but does not work as indicated above.

I've modified my SP to use a temp table rather than the CTE, and everything is working fine now.

Is there another option for dong this?
ASKER CERTIFIED SOLUTION
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dale Fye

ASKER

Thanks for the confirmation, Jim.

Dale