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
|