SQL游标比较以前的值

时间:2016-06-19 11:41:50

标签: sql sql-server cursor

我想使用光标遍历表格中的整行以找到最重的重量。这是我到目前为止提供的正确答案,但我如何使它将当前重量与先前重量进行比较,并让光标打印出最重的重量? 谢谢:))

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

2 个答案:

答案 0 :(得分:1)

您不必使用游标来执行此任务。使用游标很奇怪,因为有更好/更简单的选项:

1)如果您只需要显示最重的行,那么 CASE WHEN DENSE_RANK就足够了(这将显示所有产品的最大重量):

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)

或 2)如果你必须展示所有产品和每件产品我们必须知道它是否最重,那么{{1}}和{{1}}应该足够了:

{{1}}

Demo

答案 1 :(得分:0)

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