当我更新tsql上一条记录的OrderNo时如何更新其他OrderNo

时间:2019-05-29 14:42:50

标签: sql tsql sql-update cursor

我有一个题为“问题”的问题表,它的OrderNo定义了问题的顺序。

我在更新订单号时遇到问题。

如果我更新一个OrderNo,则必须更新所有OrderNo取决于更新的OrderNo,因此所有订单都将更新。

解决方案之一是游标,但我不能解决此问题。

您有什么建议吗?

1 个答案:

答案 0 :(得分:0)

以下代码演示了一种以给定的显示顺序重新放置行并改组其他任何行以适应更改的方法。通过使用case表达式,单个update语句可以选择如何更新不同的行。

注意:应将其包装在合适的交易中,以便在《真实话语》中使用。

-- Sample data.
declare @Samples as Table ( Id Int Identity, DisplayOrder Int );
insert into @Samples ( DisplayOrder ) values ( 1 ), ( 2 ), ( 3 ), ( 4 );
select * from @Samples order by DisplayOrder;

-- We need a few variables.
declare @PreviousDisplayOrder as Int;
declare @Id as Int, -- Row to be moved.
  @DisplayOrder as Int; -- New order for the row.

-- Pick a row to move and a new display order for it.
select @Id = 2, @DisplayOrder = 3;

-- Determine the previous display order for the row being moved.
select @PreviousDisplayOrder = DisplayOrder from @Samples where Id = @Id;

-- Display some useful tidbits.
select @PreviousDisplayOrder as PreviousDisplayOrder,
  ( select Min( DisplayOrder ) from ( values ( @DisplayOrder ), (@PreviousDisplayOrder ) ) M1( DisplayOrder ) ) as MinDisplayOrder,
  ( select Max( DisplayOrder ) from ( values ( @DisplayOrder ), (@PreviousDisplayOrder ) ) M2( DisplayOrder ) ) as MaxDisplayOrder;

-- Update the rows.
update @Samples
  set DisplayOrder = case
    -- Set the order of the repositioned row.
    when Id = @Id then @DisplayOrder
    -- Moving the repositioned row up (numerically).
    when @DisplayOrder > @PreviousDisplayOrder and DisplayOrder <= @DisplayOrder then DisplayOrder - 1
    -- Moving the repositioned row down (numerically).
    when @DisplayOrder < @PreviousDisplayOrder and DisplayOrder >= @DisplayOrder then DisplayOrder + 1
    else DisplayOrder
    end
    where
      -- Only update the rows between the original and the new display orders.
      DisplayOrder >= ( select Min( DisplayOrder ) from ( values ( @DisplayOrder ), (@PreviousDisplayOrder ) ) M1( DisplayOrder ) ) and
      DisplayOrder <= ( select Max( DisplayOrder ) from ( values ( @DisplayOrder ), (@PreviousDisplayOrder ) ) M2( DisplayOrder ) );

-- Display the results.
select * from @Samples order by DisplayOrder;