我有一个题为“问题”的问题表,它的OrderNo定义了问题的顺序。
我在更新订单号时遇到问题。
如果我更新一个OrderNo,则必须更新所有OrderNo取决于更新的OrderNo,因此所有订单都将更新。
解决方案之一是游标,但我不能解决此问题。
您有什么建议吗?
答案 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;