-2
Declare @CurrentDate   varchar(25)
Declare @PreviousDate  varchar(25)
Declare @MaxDate       varchar(25)

Declare Cursor1 Cursor  For
Select Distinct ProductID
    From   Products
    Where  ProductId Is Not Null
    Order By ProductId

Declare @ProductID varchar(14)

Open Cursor1
Fetch Next From Cursor1 Into @ProductId
While @@Fetch_Status = 0
Begin
    Select @MaxDate = Max(ProductDate)
    From   Products
    Where  ProductId = @ProductID

    Declare Cursor2 Cursor For 
    Select ProductDate 
    From   Products
    Where  ProductId = @ProductID    
    Order  By ProductDate

    Open Cursor2
    Fetch Next From Cursor2 Into @CurrentDate
    Begin Try
        While (@@Fetch_Status = 0) 
        Begin
            If @PreviousDate Is Not Null And 
               @CurrentDate Is Not Null And 
               @PreviousDate != @MaxDate
            Begin
                Update Products 
                Set ProductEndDate = @CurrentDate 
                Where ProductId = @ProductId 
                And ProductDate = @PreviousDate  
            End                 
            Set @PreviousDate  = @CurrentDate

            Fetch Next From Cursor2 Into @CurrentDate   
        End
        Close Cursor2
        Deallocate Cursor2
    End Try
    Begin Catch
        Declare @error INT,@message varchar(4000);
        Select 
            @error = error_number(), 
            @message = error_message();
        Close Cursor2
        Deallocate Cursor2
    End Catch
End 
Close Cursor1
Deallocate Cursor1
4

1 回答 1

1

如果您有重复的组合,这并不完全相同ProductID, ProductDate,但它可能会让您走上正轨:

由马丁史密斯简化

;With cte as (
    Select
        ProductID,
        ProductEndDate,
        ProductDate,
        row_number() over (partition by ProductID order By ProductDate) rn
    From
        Products
)
Update
    x
Set
    x.ProductEndDate = y.ProductDate
From
    cte x
        inner join
    cte y
        on x.ProductID = y.ProductID and
           x.rn = y.rn - 1;

Example SQLFiddle

上的索引ProductId, ProductDate将使这更快。

于 2013-10-20T14:49:59.893 回答