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
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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:
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
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