简体   繁体   中英

SQL Cursor Compare Previous Value

I want to use cursor to go through the entire line in the table to find the heaviest weight. This is what I got so far that presents the right answer but how do I make it such that it compares the Current Weight with the Previous Weight, and let the cursor print out the heaviest weight? Thanks :)

DECLARE @weight DECIMAL(8,2),
@name VARCHAR(100);

DECLARE Cursor_Eight CURSOR
FOR
SELECT Name, Weight
    FROM [SalesLT].[Product]
    ORDER BY Weight DESC;

OPEN Cursor_Eight

FETCH NEXT FROM Cursor_Eight INTO @name, @weight
PRINT @name + ' with a weight of ' + CONVERT(CHAR(8),@weight) + ' is the heaviest product.';

CLOSE Cursor_Eight 

DEALLOCATE Cursor_Eight

You don't have to use cursor for this task. It's a weird to use cursor because there are far better / simple options:

1) If you have to display only heaviest rows then TOP(1) WITH TIES and ORDER BY Weight DESC should be enough (this will show all product with max. weight):

SELECT TOP(1) WITH TIES Name, Weight
FROM (
SELECT 'A', 100 UNION ALL
SELECT 'B', 150 UNION ALL
SELECT 'C',  25 UNION ALL
SELECT 'D', 150 UNION ALL
SELECT 'E', 110 
)[Product] (Name, Weight)
ORDER BY Weight DESC

or 2) If you have to display all products and for every product we have to know if it's the heaviest or not then CASE WHEN and DENSE_RANK should be enough:

SELECT Name, Weight, 
CASE WHEN DENSE_RANK() OVER(ORDER BY Weight DESC) = 1 THEN 1 ELSE 0 END IsHeaviestProduct
FROM (
SELECT 'A', 100 UNION ALL
SELECT 'B', 150 UNION ALL
SELECT 'C',  25 UNION ALL
SELECT 'D', 150 UNION ALL
SELECT 'E', 110 
)[Product] (Name, Weight)

Demo

declare @product table (name varchar(1), weight decimal(8,2))
insert into @product values
('A',2.00),
('b',1.00),
('c',9.00),
('d',7.00),
('e',10.00),
('f',2.00)

DECLARE @weight DECIMAL(8,2),
        @maxweight DECIMAL(8,2),
        @maxname VARCHAR(100),
        @name VARCHAR(100);

DECLARE Cursor_Eight CURSOR
FOR
SELECT Name, Weight
    FROM @Product
    --ORDER BY Weight DESC;

OPEN Cursor_Eight

FETCH NEXT FROM Cursor_Eight INTO @maxname, @maxweight
WHILE @@FETCH_STATUS = 0   
BEGIN   
       FETCH NEXT FROM cursor_eight INTO @name,@weight
       if @weight > @maxweight
        begin 
            set @maxname   = @name;
            set @maxweight = @weight;
        end 
end
CLOSE Cursor_Eight 
PRINT @maxname + ' with a weight of ' + CONVERT(CHAR(8),@maxweight) + ' is the heaviest product.';
DEALLOCATE Cursor_Eight

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM