1

我使用 CROSS APPLY 参数编写了以下脚本,该脚本在我的 SQL Server 2008 开发人员数据库中运行良好,但它不适用于拥有 SQL Server 2000 数据库并且不想更改 SSMS 中的兼容性设置的客户端。

有人可以建议一种方法来转换下面的脚本以免使用 CROSS APPLY 参数吗?谢谢!

DECLARE @Flag INT
SET @Flag = 1
WHILE (@Flag < (SELECT TOP 1 (COUNT(CUSTOMERPN)) AS COUNTCUST FROM FC_Nestle
GROUP BY CustomerPN
ORDER BY COUNTCUST DESC))
BEGIN
--UPDATE AFS_TOPRODUCE COUNTS
UPDATE FC_Nestle
SET AFS_ToProduce = CustReqQty - AFS_OH
--UPDATE SUBSEQUENT AFS_OH INVENTORY COUNTS
update FC_Nestle 
set AFS_OH = - fc2.AFS_ToProduce 
from FC_Nestle 
CROSS APPLY 
(   
    select fc2.AFS_ToProduce   
    from    
    (     
        select top 1         
            fc2.AFS_ToProduce       
        from FC_Nestle fc2      
        where fc2.ForecastID < FC_Nestle.ForecastID and fc2.CustomerPN = FC_Nestle.CustomerPN     
        order by fc2.ForecastID desc   
    ) fc2   
    where fc2.AFS_ToProduce < 0 
) fc2 
where FC_Nestle.AFS_ToProduce > 0 
SET @Flag = @Flag + 1
END
4

1 回答 1

2

这应该可以帮助您:

update fc_test
   set AFS_OH = - fc2.AFS_ToProduce
  from fc_test
 -- Self join to find previous row
 inner join fc_test fc2
 -- which has lower forecastid
    on fc2.ForecastID < fc_test.ForecastID
 where fc_test.AFS_ToProduce > 0
 -- and negative afs_toproduce
   and fc2.afs_toproduce < 0
 -- and is a row immediately before
 -- ie there is no other row closer to fc_test then current fc2
   and not exists (select null 
                     from fc_test fc3
                    where fc3.forecastid > fc2.forecastid
                      and fc3.ForecastID < fc_test.ForecastID)

我使用与上次相同的表名和列名。

现场测试在Sql Fiddle

于 2012-05-07T21:55:56.023 回答