我想提取第二个_
字符之后的字符串,还要删除Microsoft SQL Server查询中的(C)
。
字段名称为资产代码
表名是dbo.DynamicsMOJ数据
数据示例:
资产代码的值
CP04K_54560_633331 (C)
CP04K_54560_641121 (C)
ME030_72159_690940 (C)
HB21M_60966_1181492 (C)
AW000_1144713 (C)
以此类推,该字段中的所有值都具有相似的格式,但是有些值只有一个“ _”
我需要获得
'633331'
'641121'
'690940'
'1181492'
'1144713'
答案 0 :(得分:1)
我的变体:
SELECT
txt,
CHARINDEX('_',REVERSE(txt)), -- there is 0 for four last examples
--REPLACE(RIGHT(txt,ISNULL(NULLIF(CHARINDEX('_',REVERSE(txt))-1,-1),LEN(txt))),' (C)','')
-- the next variants is better if we have different count of spaces before '(C)'
RTRIM(REPLACE(RIGHT(txt,ISNULL(NULLIF(CHARINDEX('_',REVERSE(txt))-1,-1),LEN(txt))),'(C)','')),
RTRIM(REPLACE(IIF(CHARINDEX('_',txt)=0,txt,RIGHT(txt,CHARINDEX('_',REVERSE(txt))-1)),'(C)',''))
FROM
(VALUES
('CP04K_54560_633331 (C)'),
('CP04K_54560_641121 (C)'),
('ME030_72159_690940 (C)'),
('HB21M_60966_1181492 (C)'),
('AW000_1144713 (C)'),
(NULL),
(''),
('1234567(C)'),
('1234567 (C)'),
('1234567')
) v(txt)
您可以使用以下查询检查数据:
SELECT *
FROM
(VALUES
('CP04K_54560_633331 (C)'),
('CP04K_54560_641121 (C)'),
('ME030_72159_690940 (C)'),
('HB21M_60966_1181492 (C)'),
('AW000_1144713 (C)'),
(NULL),
(''),
('1234567(C)'),
('1234567 (C)'),
('1234567')
) v(txt)
WHERE CHARINDEX('_',txt)=0
我认为它将为您提供所有不含'_'的值。