Question : SQL Query - Autonumbering with prefix

Hello experts,

I need help with a query.  I created a query that will look at a part and take the prefix and then add 7 digit numbering after that which will auto increment from 1 to whatever it is with leading zeros.  This works well, but then there's an issue where I need a condition.  If the part item is a fabricated part, I want it to use whatever number is already there and pad it to 7 digit numbering.  Below is an example:

These are all non-fabricated parts:

ABC1234  -->  ABC0000001
ABC2123  -->  ABC0000002
ABC398    -->  ABC0000003
DBC32      --> DBC0000001
DBC45      --> DBC0000002

These are fabricated parts and should use the same numbering but pad to 7 characters:

ACDD2343  --> ACD0002343
ACDB2321   -->ACD0002321
BAC122       -->BAC0000122

Here's my original query:

SELECT SUBSTRING(ID, 1, 3) + REPLICATE(STR(ROW_NUMBER() OVER (PARTITION BY SUBSTRING(ID, 1, 3) ORDER BY SUBSTRING(ID, 1, 3)), 7), ' ', '0') AS NEW_ID
FROM PART

Now I need to take the same part, with the first 3 letter as prefix and then whatever numeric number with 7 digits long.  Note that there are some part ID with 4 letters, it should only take the first 3 letter and then ignore whatever else.  The 2nd part where it take the number should only be numeric and then make sure it pads it with leading zeros up to 7 digits long with a total of 10 digits.  Example:  ABC0001234

Answer : SQL Query - Autonumbering with prefix

sure:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
declare @t table ( ID varchar(20) )

insert into @t values ('ABC1234')
insert into @t values ('ABC2123')
insert into @t values ('ABC398')
insert into @t values ('DBC32')
insert into @t values ('DBC45')

insert into @t values ('ACDD2343')
insert into @t values ('ACDB2321')
insert into @t values ('BAC122')



SELECT ID, SUBSTRING(ID, 1, 3) p
, ROW_NUMBER() OVER (PARTITION BY SUBSTRING(ID, 1, 3) ORDER BY SUBSTRING(ID, 1, 3)) rn
, SUBSTRING(ID, 1, 3) + RIGHT( '000000000' +  
   CASE WHEN ID LIKE '[A-Z][A-Z][A-Z][0-9]%' 
   THEN SUBSTRING(REPLACE(ID,'-',''), 4, 100)
   ELSE SUBSTRING(REPLACE(ID,'-',''), 5, 100)
   END , 7 ) x
FROM @t
Random Solutions  
 
programming4us programming4us