如果此查询从重复的表中提取,为什么需要变量?

时间:2017-05-08 22:11:03

标签: sql-server

USE AP
SELECT * INTO #InvoiceCopy FROM Invoices
DECLARE @InvoiceID int, @InvoiceTotal money
DECLARE @Total money
SET @Total = 0
WHILE @Total + (SELECT TOP 1 InvoiceTotal
 FROM #InvoiceCopy
 ORDER BY InvoiceTotal DESC) <= 200000
 BEGIN
 SELECT TOP 1 @InvoiceID = InvoiceID, @InvoiceTotal = InvoiceTotal
 FROM #InvoiceCopy
 ORDER BY InvoiceTotal DESC
 IF @InvoiceTotal < 1000
 BREAK
 ELSE
 BEGIN
 SET @Total = @Total + @InvoiceTotal
 DELETE FROM #InvoiceCopy
 WHERE InvoiceID = @InvoiceID
 END
 END
PRINT 'Total: $' + CONVERT(varchar, @Total, 1)

这是来自测试学习指南。

在制作重复表时创建invoiceID和invoiceTotal变量的目的是什么?从重复表中选择列是不是更有意义?

另外,

SET @Total = @Total + @InvoiceTotal  从#InvoiceCopy中删除  WHERE InvoiceID = @InvoiceID  END

我假设这是从表中删除少于1,000的发票。但是,我不明白怎么做。

1 个答案:

答案 0 :(得分:0)

需要这些变量来跟踪它在循环中的位置

USE AP
SELECT * INTO #InvoiceCopy FROM Invoices  --make a temp table to do calculations with
DECLARE @InvoiceID int, @InvoiceTotal money 
DECLARE @Total money
SET @Total = 0 

-- Loop while @Total plus the biggest total in the temp table is less than 200000
WHILE @Total + (SELECT TOP 1 InvoiceTotal 
                FROM #InvoiceCopy
                ORDER BY InvoiceTotal DESC) <= 200000
 BEGIN
     SELECT TOP 1 @InvoiceID = InvoiceID, @InvoiceTotal = InvoiceTotal
     FROM #InvoiceCopy
     ORDER BY InvoiceTotal DESC

    -- if the InvoiceTotal is less than 1000 then stop looping
    IF @InvoiceTotal < 1000
         BREAK
    --if it's >= 1000 then do this
    ELSE
        BEGIN
           -- Assign the current @Total plus @InvoiceTotal to the @Total variable
           SET @Total = @Total + @InvoiceTotal
           -- Remove that @InvoiceID from the temp table
           DELETE FROM #InvoiceCopy
           WHERE InvoiceID = @InvoiceID
        END
 END
PRINT 'Total: $' + CONVERT(varchar, @Total, 1)