如何在SQL Server 2008 R2中使用row_number
添加列?
BEGIN TRANSACTION
DECLARE @count int
DECLARE @maxcount int
SET @count = 1
SET @maxcount = (SELECT count(*)
FROM Applicant_Detail ad
WHERE ad.identification_code = 1)
PRINT @maxcount
WHILE (@count<@maxcount)
BEGIN
UPDATE ad
SET ad.NRIC_nbr = s.myRowNumber
FROM Applicant_Detail ad
INNER JOIN (
SELECT ROW_NUMBER() OVER (ORDER BY NRIC_nbr ASC) AS myRowNumber
FROM Applicant_Detail ad
)S
ON s.myRowNumber = @count
SET @count = @count+1
END
此查询需要花费大量时间。我在applicant_detail
表中没有任何具有顺序数据的列?我使用计数逻辑但需要很多时间?
我想要什么?
使用顺序数据更新表的列,如表1,2,3,4,5,6,7,8,9 ......最大行?
答案 0 :(得分:2)
试试这个:
declare @count int = (select count(1) from Applicant_Detail)
;with cte as
(select *, row_number() over (order by @count) rn
from Applicant_Detail)
update cte
set NRIC_nbr = rn
select * from Applicant_Detail
答案 1 :(得分:1)
解决此问题的方法
BEGIN TRANSACTION
;WITH numbering AS
( SELECT AD.NRIC_nbr,
AD.application_number,
ROW_NUMBER() OVER(ORDER BY AD.application_number) AS ROWNUMBER
FROM Applicant_Detail ad WHERE AD.identification_code=1
)
UPDATE numbering
SET NRIC_nbr=ROWNUMBER
答案 2 :(得分:-1)
当您想要使用row_numebr更新列时。这是完美的解决方案
WITH TEMP AS ( SELECT id as rid, ROW_NUMBER()OVER(ORDER BY [ID] ASC)作为RN 来自ORG ) 更新ORG设置columnname1 ='200'+(选择RN FROM TEMP,其中TEMP.rid = ORG.id)