SQL Server 2008 - 避免使用foreach循环

时间:2013-02-07 21:11:35

标签: sql-server-2008

我正在拼命避免SQL Server 2008中的foreach情况(我的背景是在c#中)。

基本上,我有一份SKU清单。对于列表中的每个SKU,我需要执行一些计算,以确定是否将在Web上显示该特定SKU。

要获取我的SKU列表,我使用它:

SELECT Feed.StyleCode as SKU
FROM [eCommerce].[dbo].[BABW_ItemFeed] as Feed
WHERE Feed.ProductDefinition = 'Kit'

返回:

enter image description here

为了计算每个SKU字段,我一直在使用它:

DECLARE @SKU AS varchar(50)
SET @SKU= '11993_16559_16227'
SELECT
    @SKU as SKU,
    0 AS Quantity,
    MIN(ISNULL(Sending.IsActive, 'WEBNO')) AS IsActive, 
    MAX(ISNULL(Sending.IsDiscontinued, 1)) AS IsDiscontinued
FROM
( 
    SELECT * FROM [eCommerce].[dbo].[Split] (
      @SKU
      ,'_') 
) AS SplitSkus 
LEFT JOIN #SkusToSend AS Sending
    ON Sending.SKU = SplitSkus.items

返回:

enter image description here

现在我需要将两个表同步,删除@SKU声明。我不认为我能够使用UNION这样做,因为第二个功能需要预先知道它将要处理的SKU ......并且JOIN需要一些东西才能加入,我不这样做真的有。是否有一些我不熟悉的功能可以用来在没有循环机制的情况下一次创建一个完整的SKU表?

2 个答案:

答案 0 :(得分:4)

尝试CROSS APPLY ...将为BABW_ItemFeed中的每一行执行UDF:

SELECT
    Feed.StyleCode as SKU,
    COUNT(*) AS Quantity,
    MIN(ISNULL(Sending.IsActive, 'WEBNO')) AS IsActive, 
    MAX(ISNULL(Sending.IsDiscontinued, 1)) AS IsDiscontinued
FROM
    [eCommerce].[dbo].[BABW_ItemFeed] as Feed 
    CROSS APPLY [eCommerce].[dbo].[Split] (Feed.StyleCode, '_') AS SplitSkus 
    LEFT JOIN #SkusToSend AS Sending
        ON Sending.SKU = SplitSkus.items
WHERE
    Feed.ProductDefinition = 'Kit'
GROUP BY
    Feed.StyleCode

答案 1 :(得分:0)

停止使用Min()和Max()...或者, pull SKU(不要使用SELECT中的参数)。

试试这个:

SELECT
    SKU,
    0 AS Quantity,
    MIN(ISNULL(Sending.IsActive, 'WEBNO')) AS IsActive, 
    MAX(ISNULL(Sending.IsDiscontinued, 1)) AS IsDiscontinued
FROM
( 
SELECT [eCommerce].[dbo].[Split] (Feed.StyleCode,'_')  as SKU
FROM [eCommerce].[dbo].[BABW_ItemFeed] as Feed
WHERE Feed.ProductDefinition = 'Kit'
) AS SplitSkus 
LEFT JOIN #SkusToSend AS Sending
    ON Sending.SKU = SplitSkus.items