SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
alter procedure [dbo].[Test7]
@Manufacturer nvarchar(20),
@literatureType nvarchar(20),
@languageCode nvarchar(20),
@modelCode nvarchar(20),
@modelYear nvarchar(20)
as
begin
select PartNum.PartNumber, ToolTip.EngText, ToolTip.FrenchText
from
(
SELECT distinct PMYM.PartNumber
FROM ProductModelYearMapping PMYM
left outer join ProductMaster PM
on PMYM.PartNumber=PM.PartNumber
left outer join ProductLiteratureType PLT
on PM.LiteratureType = PLT.Code
left outer join Model M
on PMYM.ModelCode = M.ModelCode
) as PartNum
LEFT OUTER JOIN
(
select PartNumber, EngText, FrenchText
from ToolTip
) as ToolTiP
on PartNum.PartNumber = ToolTiP.PartNumber
WHERE (
(@Manufacturer IS NULL OR M.Manufacturer = @Manufacturer) AND
(@literatureType IS NULL OR PM.LiteratureType = @literatureType) AND
(@languageCode IS NULL OR PM.LanguageCode = @languageCode) AND
(@modelCode IS NULL OR PMYM.ModelCode = @modelCode) AND
(@modelYear IS NULL OR PMYM.startyear <= @modelYear AND PMYM.endyear >= @modelYear)
)
END
我正在尝试使用结果集加入表,也必须根据我所做的某些选择来过滤结果。这就是我使用where子句的原因。但我似乎得到了这个错误。任何帮助将不胜感激。
答案 0 :(得分:0)
问题是您的WHERE
子句正在引用子查询中的别名。有两种方法可以解决这个问题。
一个修复方法是将WHERE
子句移到子查询中,其中存在别名:
select PartNum.PartNumber, ToolTip.EngText, ToolTip.FrenchText
from
(
SELECT distinct PMYM.PartNumber
FROM ProductModelYearMapping PMYM
left outer join ProductMaster PM
on PMYM.PartNumber=PM.PartNumber
left outer join ProductLiteratureType PLT
on PM.LiteratureType = PLT.Code
left outer join Model M
on PMYM.ModelCode = M.ModelCode
WHERE
(
(@Manufacturer IS NULL OR M.Manufacturer = @Manufacturer) AND
(@literatureType IS NULL OR PM.LiteratureType = @literatureType) AND
(@languageCode IS NULL OR PM.LanguageCode = @languageCode) AND
(@modelCode IS NULL OR PMYM.ModelCode = @modelCode) AND
(@modelYear IS NULL OR PMYM.startyear <= @modelYear AND PMYM.endyear >= @modelYear)
)
) as PartNum
LEFT OUTER JOIN
(
select PartNumber, EngText, FrenchText
from ToolTip
) as ToolTiP
on PartNum.PartNumber = ToolTiP.PartNumber
或者您必须在子查询中包含WHERE
子句使用的列,并更改每列的别名,类似于:
select PartNum.PartNumber, ToolTip.EngText, ToolTip.FrenchText
from
(
SELECT distinct PMYM.PartNumber,
M.Manufacturer,
PM.LiteratureType,
PM.LanguageCode,
PMYM.ModelCode,
PMYM.startyear,
PMYM.endyear
FROM ProductModelYearMapping PMYM
left outer join ProductMaster PM
on PMYM.PartNumber=PM.PartNumber
left outer join ProductLiteratureType PLT
on PM.LiteratureType = PLT.Code
left outer join Model M
on PMYM.ModelCode = M.ModelCode
) as PartNum
LEFT OUTER JOIN
(
select PartNumber, EngText, FrenchText
from ToolTip
) as ToolTiP
on PartNum.PartNumber = ToolTiP.PartNumber
WHERE
(
(@Manufacturer IS NULL OR PartNum.Manufacturer = @Manufacturer) AND
(@literatureType IS NULL OR PartNum.LiteratureType = @literatureType) AND
(@languageCode IS NULL OR PartNum.LanguageCode = @languageCode) AND
(@modelCode IS NULL OR PartNum.ModelCode = @modelCode) AND
(@modelYear IS NULL OR PartNum.startyear <= @modelYear AND PartNum.endyear >= @modelYear)
)