Search code examples
sql-serverrdbms

Looping in SQL Server Management Studio


I am given a list of 717 SKU's that I have to go through and add up the total values of Yearly Sales and Units Sold. I developed a code to search a SKU by year and receive the total amount. I was wondering If there was a way where I could loop to input a greater number of SKU's so that I don't have to go through individually SKU by SKU.

I am familiar with Loop statements but am not the best at executing them. Was wondering if there was a way to do this in the Microsoft SQL Server Management Studio 2017.

I've tried Declaring and repeating the code but it has been inefficient.

DECLARE @SDate date
SET @SDate = '01/01/2018'
DECLARE @EDate date
SET @EDate = '12/31/2018'
DECLARE @Sku varchar(20)
SET @Sku = 'SN1580' 


SELECT        SUM(Amount) AS EXPR1
FROM            dbo.[Threshold Enterprises$Sales Invoice Line]
WHERE        ([Shipment Date] BETWEEN @SDate AND @EDate) AND (No_ = N'SN1580')
SELECT        SUM(Quantity) AS EXPR1
FROM            dbo.[Threshold Enterprises$Sales Invoice Line]
WHERE        ([Shipment Date] BETWEEN @SDate AND @EDate) AND (No_ = N'SN1580')

SELECT        SUM(Amount) AS EXPR1
FROM            dbo.[Threshold Enterprises$Sales Invoice Line]
WHERE        ([Shipment Date] BETWEEN @SDate AND @EDate) AND (No_ = N'SN0350')
SELECT        SUM(Quantity) AS EXPR1
FROM            dbo.[Threshold Enterprises$Sales Invoice Line]
WHERE        ([Shipment Date] BETWEEN @SDate AND @EDate) AND (No_ = N'SN0350')

Expect the results to give me something along the lines of

SN1234
Amount 1000
Sum 200

SN3456
Amount 2000
Sum 100

Or if there was a way to get the results in a format that would be easily exportable to excel.


Solution

  • Don't think in terms of loops. Think in terms of sets.

    This uses a table variable for the sku list, but you could use a CTE, an actual table, a VALUE list; anything, really, that lets SQL Server handle all of your search terms as a data set rather than as individual inputs.

    DECLARE @SDate date = '01/01/2018'
    DECLARE @EDate date = '12/31/2018'
    
    DECLARE @Sku TABLE
    (
      Sku varchar(20)
    );
    
    INSERT @Sku (Sku)
    VALUES (N'SN1580'),
           (N'SN0350'); --<--Add your list here. Maybe use Excel to make the wrappers.
    
    SELECT        
       l.No_ 
      ,SUM(l.Amount) AS Amount
      ,SUM(l.Quantity) AS Quantity
    FROM 
      dbo.[Threshold Enterprises$Sales Invoice Line] AS l
      JOIN
       @Sku AS s
        ON s.Sku = l.No_
    WHERE
      l.[Shipment Date] BETWEEN @SDate AND @EDate
    GROUP BY
      l.No_