HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Stored Procedure with many If Else if statement

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
storedelsestatementwithproceduremany

Problem

In this Stored procedure (called by this inventory-checking function), many if else if statement are used. How can it be improved?

```
IF ( @count = 1 )
(SELECT skumaster.sku AS SKU,
( skumaster.minimumstock - Count(*) ) AS ReorderQuantity,
'LowInventory' AS Description
FROM skumaster skuMaster
JOIN inventorymaster inventoryMaster
ON skumaster.sku = inventorymaster.sku
GROUP BY skumaster.sku,
skumaster.minimumstock,
skumaster.name
HAVING Count(*) currenttimezone
--Select from Variable discount
UNION
SELECT variablediscount.sku AS SKU,
variablediscount.quantity AS ReorderQuantity,
'Variable Discount' AS descp
FROM promotionmaster
JOIN variablediscount
ON promotionmaster.promotiontypeid =
variablediscount.promotiontypeid
WHERE promotionmaster.enddate > currenttimezone)
ELSE IF( @count = 4 )
(SELECT skumaster.sku AS SKU,
( skumaster.minimumstock - Count(*) ) AS ReorderQuantity,
'LowInventory' AS Description
FROM skumaster skuMaster
JOIN inventorymaster inventoryMaster
ON skumaster.sku = inventorymaster.sku
GROUP BY skumaster.sku,
skumaster.minimumstock,
skumaster.name
HAVING Count(*) currenttimezone
--Select from Variable discount
UNION
SELECT variablediscount.sku AS SKU,
variablediscount.quantity AS ReorderQuantity,
'Variable Discount' AS

Solution

I see seven independent queries. There is no reason to put them all in one stored procedure that dispatches based on the @count parameter. (Furthermore, it shouldn't be named "count". "Mode" would be more appropriate.)

Once you treat them as independent queries, there is no need for a stored procedure anymore. You could create seven VIEWs instead. The views that involve a UNION could even reference other views, to reduce code duplication.

Context

StackExchange Code Review Q#52590, answer score: 3

Revisions (0)

No revisions yet.