Here's one idea...
DECLARE @your_table table (
columnvalue varchar(50)
);
INSERT INTO @your_table (columnvalue)
VALUES ('P0987799')
, ('R0987884')
, ('9745456')
, ('RT087477')
;
-- Verbose version (shows individual steps)
SELECT columnvalue
, start_of_numbers
, numeric_part
, 'P' + numeric_part As prefixed_with_p
FROM (
SELECT columnvalue
, start_of_numbers
, SubString(columnvalue, start_of_numbers, 50) As numeric_part --50 = length of field (varchar(50))
FROM (
SELECT columnvalue
, PatIndex('%[0-9]%', columnvalue) As start_of_numbers -- find the first number
FROM @your_table
) As x
) As y
;
-- Shortened version
SELECT columnvalue
, 'P' + SubString(columnvalue, PatIndex('%[0-9]%', columnvalue), 50) As prefixed_with_p
FROM @your_table
;
Start by finding where the first numeric character is, then strip off anything before that point (leaving just the number). Then stick a "P" on the beginning!
Results:
columnvalue start_of_numbers numeric_part prefixed_with_p
------------ ----------------- ------------- ----------------
P0987799 2 0987799 P0987799
R0987884 2 0987884 P0987884
9745456 1 9745456 P9745456
RT087477 3 087477 P087477
columnvalue prefixed_with_p
------------ ----------------
P0987799 P0987799
R0987884 P0987884
9745456 P9745456
RT087477 P087477
EDIT: if you want to narrow down your prefix scope:
SELECT columnvalue
, start_of_numbers
, numeric_part
, alpha_part
, CASE WHEN alpha_part IN ('P', 'R', 'RT') THEN -- limit the prefixing
'P' + numeric_part
ELSE
numeric_part
END As prefixed_with_p
FROM (
SELECT columnvalue
, start_of_numbers
, SubString(columnvalue, start_of_numbers, 50) As numeric_part --50 = length of field (varchar(50))
, SubString(columnvalue, 0, start_of_numbers) As alpha_part
FROM (
SELECT columnvalue
, PatIndex('%[0-9]%', columnvalue) As start_of_numbers
FROM @your_table
) As x
) As y
;
Results:
columnvalue start_of_numbers numeric_part alpha_part prefixed_with_p
------------ ----------------- ------------- ----------- ----------------
P0987799 2 0987799 P P0987799
R0987884 2 0987884 R P0987884
9745456 1 9745456 9745456
RT087477 3 087477 RT P087477