briangriffin
Programmer
I'm trying to update a summary table multiple times using a cte for the values - it works fine the first time, but then I get "Invalid object name cte_receipts"
This works:
But adding additional updates generates the error:
Surely I won't need to redeclare the cte for each update - what am I missing?
Thanks in advance.
This works:
Code:
with cte_receipts as
(select
BillingID,
InsuranceID,
count(BillingID) as ReceiptCount,
sum(Amount) as ReceiptTotal,
max(BatchDateTime) as LatestReceipt
from Livendb.dbo.BarCollectionTransactions
where Type = 'R'
group by BillingID, InsuranceID)
update OSUMC_MT6.dbo.OSUMC_BarSummary
set Insurance1NumberOfReceipts = b.ReceiptCount,
Insurance1LatestReceipt = b.LatestReceipt
from OSUMC_MT6.dbo.OSUMC_BarSummary a inner join cte_receipts b
on a.BillingID = b.BillingID
and a.Insurance1 = b.InsuranceID;
But adding additional updates generates the error:
Code:
with cte_receipts as
(select
BillingID,
InsuranceID,
count(BillingID) as ReceiptCount,
sum(Amount) as ReceiptTotal,
max(BatchDateTime) as LatestReceipt
from Livendb.dbo.BarCollectionTransactions
where Type = 'R'
group by BillingID, InsuranceID)
update OSUMC_MT6.dbo.OSUMC_BarSummary
set Insurance1NumberOfReceipts = b.ReceiptCount,
Insurance1LatestReceipt = b.LatestReceipt
from OSUMC_MT6.dbo.OSUMC_BarSummary a inner join cte_receipts b
on a.BillingID = b.BillingID
and a.Insurance1 = b.InsuranceID
[bold]
update OSUMC_MT6.dbo.OSUMC_BarSummary
set Insurance2NumberOfReceipts = c.ReceiptCount,
Insurance2LatestReceipt = c.LatestReceipt
from OSUMC_MT6.dbo.OSUMC_BarSummary a inner join cte_receipts c
on a.BillingID = c.BillingID
and a.Insurance2 = c.InsuranceID
[/bold]
Surely I won't need to redeclare the cte for each update - what am I missing?
Thanks in advance.