SQL Server 2008 - Avoiding Foreach Loops
I'm trying desperately to avoid a foreach situation in SQL Server 2008 (my background is in C #).
Basically, I have a SKU list. For each SKU in the list, I need to do some calculations that determine if that particular SKU will show up on the internet.
To get a list of SKUs I use this:
SELECT Feed.StyleCode as SKU
FROM [eCommerce].[dbo].[BABW_ItemFeed] as Feed
WHERE Feed.ProductDefinition = 'Kit'
Return:
And to calculate each SKUs box I used this:
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
Return:
Now I need to sync the two tables together by removing the @SKU declaration. I don't think I can use UNION to do this, because the second function requires prior knowledge of the SKU to be processed ... and the JOIN will require something to join, there really is. Is there some function I'm not familiar with that I can use to create a complete SKU table in one pass without a looping mechanism?
source to share
Try CROSS APPLY
... which will execute your UDF for each line in BABW_ItemFeed
:
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
source to share
Stop using Min () and Max () ... or else, pull the SKU (don't use a parameter in SELECT).
Try the following:
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
source to share