How to update colum serial where is null by max+1 ?

ahmed salah 3,216 Reputation points
2021-03-10T03:24:16.7+00:00

I work on SQL server 2012 I face issue i can't update column serial by max + 1
where is have null value on on serial column
partnumber is unique on table
so i need to get max number from serial and increment it by 1
then assign it to null on serial column

meaning any partnumber is unique and have null on serial
must have unique number on serial by max number on serial +1
for every part number

create table #test
(
partNumber  nvarchar(200),
serialNumber  int
)
insert into #test(partNumber,serialNumber)
values
('nna5',9),
('nfggg',20),
('ddfg',10),
('llm',NULL),
('109',NULL),
('8654',NULL),
('1234',30)

expected result

partNumber serialNumber
llm 31
109 32
8654 33

Developer technologies | Transact-SQL
SQL Server | Other
0 comments No comments
{count} votes

Accepted answer
  1. EchoLiu-MSFT 14,621 Reputation points
    2021-03-10T05:51:07.757+00:00

    Try:

         ;WITH cte  
         AS(SELECT *,ROW_NUMBER() OVER(ORDER BY partNumber) rr FROM #test WHERE serialNumber IS NULL)  
          
         UPDATE c  
         SET serialNumber=(SELECT MAX(serialNumber) FROM #test)+rr  
         FROM cte c  
    

    76153-image.png

    The final result is slightly different from what you expect because of sorting by partNumber.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Nandan Hegde 36,146 Reputation points MVP Volunteer Moderator
    2021-03-10T04:23:34.017+00:00

    Hey @ahmed salah ,
    You can achieve this by the below process:

    1. Initially insert the data as is meaning NULL values be inserted as NULL itself
    2. Then take a count of records where that column is null
    3. then using while loop iteratively update the rows for that column as
      Select max(serialNumber) +1 from #test

    This should help you achieve your results but not sure whether this is the most clean way to do it

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.