I have not been able to figure out scope of reference when there are nested queries. For example I can’t seem to reference NoCarsFound.CU in my inner join. I don’t understand why in my join I can’t reference previous result sets…I think I just don’t undrestand the scope of referencing previous select results or referencing aliases in my inner join’s ON comparisons.
I also get Ambiguous column name ‘CU’
So I keep getting errors saying it doesn’t know NoCarsFound.CU. I even tried to reference a straight view such as vwInvalidCars.CU, and it doesn’t understand vwInvalidCars either.
create procedure [Rac].[GetCarStatDetails_sp]
@Year int,
@CarTitle varchar(30),
@Company varchar(31),
@CU varchar(12),
@UserName varchar(50)
as
BEGIN
DECLARE @CarMatch table
(
FaceValueTol varchar(100),
FaceValueDesc varchar(100),
Year int,
CU varchar(16),
PaintTypeDesc varchar(50)
)
insert into @CarMatch
Select temp1.FaceValueTol,
temp1.FaceValueDesc,
temp1.Year,
temp1.CU,
temp1.PaintTypeDesc
from Rac.viewCarBase as temp1
join (select Username, userCars.CU from Nep.viewUserCars userCars where UserName = @UserName) as userCars on userCars.CU = temp1.CU
INNER JOIN
(
Select CU,
from Rac.vwCarFactor carfactors
where RiskFactorTypeID not in (334,553,34334,534,7756)
Group by CU
) as temp
on
and temp1.CU = temp.CU
and temp1.PaintTypeDesc = temp.CalcPaintTypeDesc
Where
temp1.RiskFactorTypeID=4
and temp1.[Year]=@Year
and (temp1.CarTitle=@CarTitle or @CarTitle='<All>')
and (temp1.CU=@CU or @CU='<All>')
SELECT ProductID_bo,
Coalesce(CarTitle_bo,LTRIM(RTRIM(CarTitle))) as CarTitle,
Coalesce(Company_bo,LTRIM(RTRIM(Company))) as Company,
Coalesce(CU_bo,LTRIM(RTRIM(CU))) as CU
FROM
Rac.viewCarBase as NoCarsFound
join (select Username, userCars.CU from Nep.viewUserCars userCars where UserName = @UserName) as userCars on userCars.CU = NoCarsFound.CU
LEFT OUTER JOIN
(
Select ProductID_bo,
CarTitle_bo,
Company_bo,
CU_bo,
from (
SELECT ProductID as ProductID_bo,
LTRIM(RTRIM(CarTitle)) as CarTitle_bo,
LTRIM(RTRIM(Company)) as Company_bo,
FROM Rac.viewCarBase
join (select Username, userCars.CU from Nep.viewUserCars userCars where UserName = @UserName) as userCars on userCars.CU = Rac.viewCarBase.CU
where ProductID in (Select ProductID from @CarMatch) and
and (CarTitle=@CarTitle or @CarTitle='<All>')
and (Company=@Company or @Company='<All>')
and (CU=@CU or @CU='<All>')
) AS SUB1
Group By
CarTitle_bo,
Company_bo,
CU_bo,
ON
NoCarsFound.CU = CarsFoundDeals.CU_bo
where
and (CarTitle=@CarTitle or @CarTitle='<All>')
and (Company=@Company or @Company='<All>')
and (CU=@CU or @CU='<All>')
end
I would look at the two following pieces of SQL from what you have above:
and
Both of these appear to be referencing
CUin a way that could potentially cause the error you are reporting.