交叉应用语法

时间:2014-01-30 15:10:44

标签: sql sql-server cross-apply

我有一个查询,我认为使用交叉申请会更有效率。我已经将语法从连接更改为交叉应用,但我收到了一般语法错误:

  

Msg 170,15级,状态1,第14行   第14行:'apply'附近的语法不正确。   信息156,第15级,状态1,第21行   关键字'as'附近的语法不正确。

这是我第一次使用交叉应用,我没有看到语法错误(至少在与我发现的示例比较时)。这是代码:

Select v.PC_ID
, v.PC_Name
, v.LOB
, v.REG
, v.DST
, v.PC
, d.Effective_Date as DateOfLastInc
, p.TotalPriceIncPct
, p.last_update_by
, d.PlanEffective_Date
, p2.PlanTotalPriceIncPct
--INTO #temp1
from v_PC_Profile v
cross apply (
    Select pc_id
, Effective_Date=max(Effective_Date)
, PlanEffective_Date=max(PlanEffective_Date) 
from dbo.Price_Inc_PC_Details
where pc_id = v.pc_id
group by pc_id
) as d --on d.PC_ID=v.PC_ID
left join dbo.Calendar c on c.FULL_DATE=d.Effective_Date 
left join dbo.Price_Inc_PC_Details p on d.PC_ID=p.PC_ID and d.Effective_Date=p.Effective_Date
left join dbo.Price_Inc_PC_Details p2 on d.PC_ID=p2.PC_ID and         d.PlanEffective_Date=p2.PlanEffective_Date --added by ajl 1/15/2013

WHERE segment NOT IN ('Closed', 'Overhead')
and segment not like '%closed%'
and Close_Date is NULL

group by v.PC_ID
, v.PC_Name
, v.PC
, d.Effective_Date
, p.TotalPriceIncPct
, d.PlanEffective_Date
, p2.PlanTotalPriceIncPct
, v.REG
, v.DST
, v.LOB
, p.last_update_by
, p.PlanEffective_Date
, p.PlanTotalPriceIncPct
order by v.PC_ID

非常感谢任何帮助!

SD

3 个答案:

答案 0 :(得分:7)

以前版本的SQL Server中兼容级别为80(a.k.a SQL Server 2000)的数据库为UDF提供了此错误。

语法看起来没问题并在我的SQL Server 2012上解析OK。 我在SQL Server 2008 R2上创建了一个数据库,其兼容级别为80,但解析确定。

请参阅MSDN上的"Using APPLY"

  

要使用APPLY,数据库兼容级别必须至少为90。

答案 1 :(得分:1)

事实证明它出现在SQL Server 2000上。我不知道我们有比2005年更高的版本。非常感谢所有人!

答案 2 :(得分:0)

似乎在交叉应用运算符之后的子查询中,'group by'和'where'的顺序应该互换:

(
Select pc_id
, Effective_Date=max(Effective_Date)
, PlanEffective_Date=max(PlanEffective_Date) 
from dbo.Price_Inc_PC_Details
group by pc_id
having pc_id = v.pc_id
) as d

请尝试一下,看看它是否可以解决您的问题,因为这不会改变您想要达到的效果。

此外,在查询的fag末端的group by似乎服务于“DISTINCT”的目的。

相关问题