这里有一个想法......
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
;
首先找到第一个数字字符的位置,然后去掉该点之前的所有内容(只留下数字)。然后在开头贴一个“P”!
结果:
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
编辑:如果您想缩小前缀范围:
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
;
结果:
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