4

读完这个问题后,我还有另一个类似的问题。有没有一种简单的方法可以让这个 SQL 语句工作?

update [Insurances] set [RowNo]=ROW_NUMBER() over (order by [RowNo])

我有一RowNo列要在删除记录时更新。

4

3 回答 3

9
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
于 2012-09-12T14:40:52.343 回答
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;

希望这可以帮助。

于 2012-09-12T14:39:54.300 回答
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
于 2015-03-10T14:39:03.167 回答