这是我的桌子:
ID int (Primary Key)
Name
Order
我正在尝试向上/向下移动我的行。所以我想更新订单字段。
UPDATE Technology
SET Order = Order + 1
WHERE ID = 2;
我猜你对 column name 有问题order
。order
是一个关键字,所以你不能直接使用它。试试这个方法:
Update Technology set [Order]=[Order]+1 Where ID=2
尝试这个:
update menu
set [order]=m2.[order]+1
from menu
join menu m2 on menu.[Order]= m2.[Order]-1
好的,假设您想在两个项目之间进行交换操作,您可以更改 SET 子句中的逻辑。
--table setup
CREATE TABLE #Technology
(
Id int,
[Order] int,
Name varchar(10)
)
INSERT INTO
#Technology
(
Id,
[Order],
Name
)
VALUES
(1, 1, 'Menu1'),
(2, 2, 'Menu2'),
(0, 0, 'Menu0'),
(3, 3, 'Menu3')
--proof of original order
SELECT
*
FROM
#Technology
UPDATE
#Technology
SET
[Order] =
(
SELECT
[Order]
FROM
#Technology T1
WHERE
Id IN (1, 2)
AND #Technology.Id <> T1.Id -- get the order of the *other* item in the pair
) -- this subquery works because we only have two ids do work with
WHERE
Id IN (1, 2)
--new order
SELECT
*
FROM
#Technology
UPDATE Technology SET [Order] = [Order] + 1 WHERE [Order] >= ( SELECT [Order] FROM Technology WHERE ID = 2 )
这将确保没有重复的订单(如果不存在的话)。
因为您只更新一条记录,即 ID=2 的记录,所以显然它的order
编号与(我假设)ID=3 的记录相同。
您可能希望order
为所有 ID 增加所有数字。这样您的表中就不会出现重复的订单号。为此,只需运行不带该WHERE
子句的查询。
Update Technology
set Order=Order+1
我认为从您的评论中您想交换两个订单。我可能会用存储过程来做到这一点
CREATE PROC swapOrders @order1 int, @order2 int
AS BEGIN
IF NOT EXISTS (SELECT * FROM Technology WHERE order = @order1)
OR NOT EXISTS (SELECT * FROM Technology WHERE order = @order2)
RETURN --if either of the orders aren't valid don't do anything. You may want to log or raise an error here
ELSE
UPDATE Technology
SET order = CASE order WHEN @order1 THEN @order2 WHEN @order2 THEN @order1 ELSE order END
END
这是假设顺序是唯一的