Suppose, you have coded the following script in your SQL Server stored procedure.
DECLARE @unitPrice int
DECLARE @qty int
DECLARE @total int
DECLARE @grandTotal int
SET @grandTotal = 0
DECLARE cursorTxn CURSOR FOR
SELECT unitPrice, qty
FROM Transactions
OPEN cursorTxn
FETCH NEXT FROM cursorTxn INTO @unitPrice, @qty
WHILE @@FETCH_STATUS = 0
BEGIN
SET @total = (@unitPrice * @qty)
SET @grandTotal = @grandTotal + @total
FETCH NEXT FROM cursorTxn INTO @unitPrice, @qty
END
CLOSE cursorTxn
DEALLOCATE cursorTxn
This snippet works fine, calculates the correct grand total of all the transactions and return the result to the caller. One can say that it is a stable procedure and does the job well. However, if he checks his code after few months and he has already polished his skillsets, he may call this piece of code a crap. He can easily upgrade this piece of code by using the following alternative.
DECLARE @grandTotal int
SELECT @grandTotal = SUM(unitPrice * qty)
FROM Transactions
The above code will return the same result but in a much optimized way.