简体   繁体   中英

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?

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? 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?

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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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