请告诉我如何仅提取
IMIS Event - BITWN1802
部分来自以下文字(离开T1或T1 S1)。
我尝试用_
(下划线符号)替换空格以找到其charindex
,因此我可以使用上一个charindex
的{{1}}位置和子串它,但它没有那样工作。
_
预期结果:
感谢您的帮助
答案 0 :(得分:2)
如果您想从头开始使用固定长度的字符,则可以使用LEFT
,因此查询将为:
SELECT LEFT([Code], 22) AS [Code]
答案 1 :(得分:1)
请尝试这样 -
CREATE TABLE sts
(
Vals VARCHAR(200)
)
GO
INSERT INTO sts VALUES
('IMIS Event - BITWN1802 ')
,('IMIS Event - BITWN1802 T1 T2')
,('IMIS Event - BITWN18023 T1 T2')
,('IMIS Event - BITWN1801 T1 T2')
,('IMIS Event - BITWN1802 X')
,('')
,(NULL)
GO
SELECT IIF(a<>0,SUBSTRING(Vals,CHARINDEX('IMIS Event - BITWN', Vals , 0),CHARINDEX(' ', Vals , a)),Vals) Vals
FROM
(
SELECT
*,
IIF(CHARINDEX('IMIS Event - BITWN', Vals , 0)>0, CHARINDEX('IMIS Event - BITWN', Vals , 0) + LEN('IMIS Event - BITWN')
,0) a
FROM sts
)x
输出
Vals
------------------------------
IMIS Event - BITWN1802
IMIS Event - BITWN1802
IMIS Event - BITWN18023
IMIS Event - BITWN1801
IMIS Event - BITWN1802
NULL
(7 rows affected)
答案 2 :(得分:0)
SELECT SUBSTRING([Code], 1, CHARINDEX(' ', [Code] + ' ', CHARINDEX('BITWN', [Code])))
答案 3 :(得分:0)
试试这个
DECLARE @Table AS TABLE (Data varchar(100))
INSERT INTO @Table
SELECT 'IMIS Event - BITWN1802 T2' UNION ALL
SELECT 'IMIS Event - BITWN1802 T1' UNION ALL
SELECT 'IMIS Event - BITWN1802 T1 S1'
SELECT Data,
CONCAT(SUBSTRING(Data,0,CHARINDEX('-',Data)-1),' - ',SUBSTRING(ReqData,0,CHARINDEX(' ',ReqData))) As ReqData
FROM
(
SELECT Data, LTRIM(SUBSTRING(Data,CHARINDEX('-',Data)+1,LEN(Data))) As ReqData
FROM @Table
)dt
结果
Data ReqData
-------------------------------------------------------
IMIS Event - BITWN1802 T2 IMIS Event - BITWN1802
IMIS Event - BITWN1802 T1 IMIS Event - BITWN1802
IMIS Event - BITWN1802 T1 S1 IMIS Event - BITWN1802