我是一个sql noob,我需要关于如何使用set命令来分配sortorder列的值的语法帮助。以下代码不会更新表,但这是我希望它看起来的样子(所有排序订单值都设置为0(。我可以手动进行,但要寻找快速替代方案(数据集更大一些(。
Select ROW_NUMBER() OVER (ORDER BY Name ASC) AS SortOrder, Name
From DesignColours
SortOrder |Name
1 Beige
2 Black
3 Blue
4 Brown
5 Copper
感谢您的帮助
您可以从下面的CTE中受益,假设您使用的是SQL Server,并且您的原始表已经具有诸如SortOrder之类的列:
;with cte (SortOrder, Name) as (
Select ROW_NUMBER() OVER (ORDER BY Name ASC) AS SortOrder, Name
From DesignColours
)
update d
set d.SortOrder = cte.SortOrder
from DesignColours d
inner join cte on d.Name = cte.Name
如果没有排序列已经存在,则可以:
ALTER TABLE DesignColours
ADD SortOrder int
GO
定期使用更新语句的用法是:
UPDATE tablename
set columnName = yourvalue
where <yourrule>
参考:https://www.w3schools.com/sql/sql_update.asp
update a
set a.SortOrder = b.SortOrder
from DesignColours a
join
(Select ROW_NUMBER() OVER (ORDER BY Name ASC) AS SortOrder, Name
From DesignColours)b
on a.Name = b.Name