不要修改主键,因为您有要插入的新记录,所以这不是修改输出顺序的好方法。
在表格上添加一个新列来保存您的订单。然后,您可以将主键值复制到该列(如果这是您当前的顺序),然后再对新行进行所需的更改。
您应该能够复制和粘贴并按原样运行的示例:
我添加了orderid 列,您需要使用默认空值来处理。
DECLARE @OrderTable AS TABLE
(
id INT ,
val VARCHAR(5) ,
orderid INT
)
INSERT INTO @OrderTable
( id, val, orderid )
VALUES ( 1, 'aaa', NULL )
,
( 2, 'bbb', NULL )
,
( 3, 'ddd', NULL )
SELECT *
FROM @OrderTable
-- Produces:
/*
id val orderid
1 aaa NULL
2 bbb NULL
3 ddd NULL
*/
-- Update the `orderid` column to your existing order:
UPDATE @OrderTable
SET orderid = id
SELECT *
FROM @OrderTable
-- Produces:
/*
id val orderid
1 aaa 1
2 bbb 2
3 ddd 3
*/
-- Then you want to add a new item to change the order:
DECLARE @newVal AS NVARCHAR(5) = 'ccc'
DECLARE @newValOrder AS INT = 3
-- Update the table to prepare for the new row:
UPDATE @OrderTable
SET orderid = orderid + 1
WHERE orderid >= 3
-- this inserts ID = 4, which is what your primary key would do by default
-- this is just an example with hard coded value
INSERT INTO @OrderTable
( id, val, orderid )
VALUES ( 4, @newVal, @newValOrder )
-- Select the data, using the new order column:
SELECT *
FROM @OrderTable
ORDER BY orderid
-- Produces:
/*
id val orderid
1 aaa 1
2 bbb 2
4 ccc 3
3 ddd 4
*/