SQL 如何在分隔符后拆分字符串

SQL how to split string after delimiter

我正在 SSMS 中创建查询,我相信我们使用的是 Server 2012。我有大约一个月的 SQL 经验,所以我对此很陌生。

我有一个字母数字字符串,我正试图将其拆分,这样我就可以拥有一个仅包含数字的列。字符串以 2-4 个数字开头,可能包含也可能不包含 '|'作为分隔符,结尾有 3-4 个字符。

如何才能像这样分隔列?

Current     Numbers   Everything else
461|CNC     461       |CNC
1147|CNC    1147      |CNC
1103FCR     1103      FCR

当前代码

SELECT
    a.CTI_EMP_ID,
    a.DS_LOAD_DT,
    a.DURATIONSEC,
    a.LGCY_SPSR_ID,
    a.MSG_TYPE_CD,
    a.SPSR_CLS_NM
FROM DW_RawData_CTIDetail a
LEFT JOIN DW_Dim_AssociateMapping b 
    ON a.CTI_EMP_ID = b.CTI_ID AND a.DS_LOAD_DT = b.ScheduleDate
WHERE 
    b.MUID = '400'
    AND a.DS_LOAD_DT >= '2019-08-01'
ORDER BY DS_LOAD_DT DESC

您可以使用patindex()来定位字符串中最后一位数字的位置,例如:

patindex('%[0-9][^0-9]%', mycol)

然后您可以在查询中使用它:

select 
    left(mycol, patindex('%[0-9][^0-9]%', mycol)) mydigits,
    right(mycol, len(mycol) - patindex('%[0-9][^0-9]%', mycol)) mychars
from t

Demo on SQLServer 2012 DB Fiddle:

with t as (
    select '461|CNC' mycol
    union all select '1147|CNC'
    union all select '1103FCR'
)
select 
    mycol,
    left(mycol, patindex('%[0-9][^0-9]%', mycol)) mydigits,
    right(mycol, len(mycol) - patindex('%[0-9][^0-9]%', mycol)) mychars
from t
GO
mycol    | mydigits | mychars
:------- | :------- | :------
461|CNC  | 461      | |CNC   
1147|CNC | 1147     | |CNC   
1103FCR  | 1103     | FCR