How to add leading zeros to exist id

Riley 380 Reputation points
2023-09-28T03:45:51.0966667+00:00

Need to add leading zeros to the id based on the max id.

Sample data:

create table test2 (id int,val varchar(20))
insert into test2 values(1,'aaa'),(11,'bbb'),(111,'ccc')
select * from test2

Result:

User's image

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,670 questions
0 comments No comments
{count} votes

Accepted answer
  1. LiHongMSFT-4306 26,706 Reputation points
    2023-09-28T03:57:25.1466667+00:00

    Hi @Riley

    If I understand right, you could use format like this:

    SELECT T.*,FORMAT(id,REPLICATE('0',LEN(max_id))) AS new_id
    FROM test2 T CROSS APPLY (SELECT MAX(id)AS max_id FROM test2)C
    

    Best regards,

    Cosmog Hong

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 44,296 Reputation points
    2023-09-28T05:03:17.4633333+00:00

    Numeric values never have leading zero, in no system. You have to convert it to a string, add some "0" at the front and take the right part in length as you want to have it, e.g. 6 :

    declare @test2 table (id int,val varchar(20))
    insert into @test2 values(1,'aaa'),(11,'bbb'),(111,'ccc')
    
    select t.*, right('000000' + CONVERT(varchar(9), t.id), 6) as new_id
    from @test2 as t
    
    
    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.