Tuesday, February 14, 2023

How to add the prefix to the ID column with auto increment ID in SQL?

Here, I am taking an example of a Product. We have different types of  products, so I want to generate a new ProductId using a prefix of value like the below:


Taking the example of "Vanilla Ice-cream", Now I want to generate an id with the prefix "Ice-Vanila-" with autoincrement number having the length of 7.


In the first step, I am going to add two Products using the below queries:
---------------------------------------------------------------------------
Create Table  #Test
(
 Id Int Identity(1,1),
 PId As 'Ice-Vanila-' + Replace(Str(Id, 7), Space(1), '0')
)

Insert Into #Test Default Values
Insert Into #Test Default Values

Select * From #Test

--Drop table #Test

---------------------------------------------------------------------------
Result:



---------------------------------------------------------------------------
Now I am adding new records to check, will this work?
---------------------------------------------------------------------------
Insert Into #Test Default Values
Insert Into #Test Default Values
Insert Into #Test Default Values

Select * From #Test

---------------------------------------------------------------------------
Result: Yeah!, It's working 



No comments:

Post a Comment