简体   繁体   English

如何在SQL Server中使用row_number更新列?

[英]How can I update a column with row_number in SQL Server?

How can I udpate a column with row_number in SQL Server 2008 R2? 如何在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

This query takes a lot of time. 该查询需要很多时间。 I do not have any column in the applicant_detail table which has sequential data? 我在applicant_detail表中没有任何具有顺序数据的列? I use the count logic but takes lot of time? 我使用计数逻辑,但是需要很多时间吗?

What i want? 我想要的是?
Update the column of the table with sequential data like 1,2,3,4,5,6,7,8,9...... max row of the table? 使用顺序数据(例如1,2,3,4,5,6,7,8,9 ......)更新表的列吗?

Try this: 尝试这个:

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

Demo 演示版

Solution for this problem 解决这个问题

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

when you want to update the column with row_numebr. 当您想使用row_numebr更新列时。 it is the perfect solution 这是完美的解决方案

WITH TEMP AS ( SELECT id as rid, ROW_NUMBER() OVER (ORDER BY [ID] ASC) AS RN FROM ORG ) update ORG Set columnname1 ='200'+(select RN FROM TEMP where TEMP.rid=ORG.id) 使用TEMP AS(将SELECT ID作为rid,将ROW_NUMBER()覆盖(按ORDER BY [ID] ASC)作为RN FROM ORG)更新ORG设置columnname1 ='200'+(选择RN FROM TEMP,其中TEMP.rid = ORG.id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM