I'm running the following query, but getting the error saying that my table variables don't exist in the last query. Can anyone see why this is happening and how to correct?
DECLARE @customers Table(custName varchar(20), custCode varchar(10) )
INSERT INTO @customers
select distinct JM.CustLongName, JM.CustomerCode
From Jobmaster JM
WHERE StartDate > '20091031'
DECLARE @Oct Table(custCode varchar(10), PromiseAvg decimal(10,4), ShipAvg decimal(10,4) )
--The following statement is run 12 times with the different months of the year
INSERT INTO @Oct
SELECT JM.CustomerCode
, isnull(AVG(Cast(DATEDIFF(dd, ISNULL(startDate, 0), ISNULL(PromiseDate, 0)) As Decimal)),0) As PromiseAvg
, isnull(AVG(Cast(DATEDIFF(dd, ISNULL(startDate, 0), ISNULL(BOL.ShipDate, 0)) As Decimal)),0) As ShipAvg
from jobitems JI
LEFT JOIN jobmaster JM ON JI.Job_Number = JM.JobNumber
LEFT JOIN dbo.NCL_BOLDetails BD ON JM.JobNumber = BD.JobNumber AND JI.Item_Code = BD.ItemNumber
INNER JOIN dbo.NCL_BOLs BOL ON BD.BOLID = BOL.BOLID
WHERE StartDate BETWEEN '20101001' AND '20101031'
Group By JM.CustomerCode, JM.CustLongName
Order By JM.CustomerCode
/*....copies removed for brevity.....*/
Select [@customers].custCode, [@customers].custName
, [@Nov].PromiseAvg, [@Nov].ShipDate
, [@Dec].PromiseAvg, [@Dec].ShipDate
, [@Jan].PromiseAvg, [@Jan].ShipDate
, [@Feb].PromiseAvg, [@Feb].ShipDate
, [@Mar].PromiseAvg, [@Mar].ShipDate
, [@Apr].PromiseAvg, [@Apr].ShipDate
, [@May].PromiseAvg, [@May].ShipDate
, [@Jun].PromiseAvg, [@Jun].ShipDate
, [@Jul].PromiseAvg, [@Jul].ShipDate
, [@Aug].PromiseAvg, [@Aug].ShipDate
, [@Sep].PromiseAvg, [@Sep].ShipDate
, [@Oct].PromiseAvg, [@Oct].ShipDate
FROM @customers
LEFT JOIN [@Nov] ON [@customers].custCode = [@Nov].custCode
LEFT JOIN [@Dec] ON [@customers].custCode = [@Dec].custCode
LEFT JOIN [@Jan] ON [@customers].custCode = [@Jan].custCode
LEFT JOIN [@Feb] ON [@customers].custCode = [@Feb].custCode
LEFT JOIN [@Mar] ON [@customers].custCode = [@Mar].custCode
LEFT JOIN [@Apr] ON [@customers].custCode = [@Apr].custCode
LEFT JOIN [@May] ON [@customers].custCode = [@May].custCode
LEFT JOIN [@Jun] ON [@customers].custCode = [@Jun].custCode
LEFT JOIN [@Jul] ON [@customers].custCode = [@Jul].custCode
LEFT JOIN [@Aug] ON [@customers].custCode = [@Aug].custCode
LEFT JOIN [@Sep] ON [@customers].custCode = [@Sep].custCode
LEFT JOIN [@Oct] ON [@customers].custCode = [@Oct].custCode