阅读this question后,我有另一个类似的问题。是否有一种简单的方法可以使这个SQL语句起作用?
update [Insurances] set [RowNo]=ROW_NUMBER() over (order by [RowNo])
我有一个RowNo
列,我想在删除记录时更新。
答案 0 :(得分:8)
UPDATE t1
SET t1.RowNo = s.RowNo
FROM [Insurances] t1
INNER JOIN
(
SELECT Id, ROW_NUMBER() OVER( ORDER BY Somefield DESC) RowNo
FROM Insurances
) s ON t1.Id = s.Id
答案 1 :(得分:2)
我会将表连接到子查询(不确定您是否可以在SQL Server中执行此操作)或创建视图并将表连接到更新中的表:
CREATE VIEW InsurancesView AS
SELECT insuranceID, ROW_NUMBER() OVER ( ORDER BY RowNo ) AS newRowNo
FROM Insurances;
(假设您有一个名为insuranceID
的主键)
UPDATE Insurances AS i
INNER JOIN InsurancesView AS iv
ON i.insuranceID = iv.insuranceID
SET i.RowNo = iv.newRowNo;
希望这有帮助。
答案 2 :(得分:2)
WITH cte AS
(
SELECT Id, ROW_NUMBER() OVER(ORDER BY Name ) RowNo FROM lu_Domain
)
UPDATE dbo.lu_Domain
SET SortOrder = cte.RowNo
FROM dbo.lu_Domain d
INNER JOIN cte ON cte.id = d.Id