SQL Server中文本的子串部分

时间:2018-05-09 08:13:59

标签: sql sql-server

请告诉我如何仅提取

IMIS Event - BITWN1802 

部分来自以下文字(离开T1或T1 S1)。

我尝试用_(下划线符号)替换空格以找到其charindex,因此我可以使用上一个charindex的{​​{1}}位置和子串它,但它没有那样工作。

_

enter image description here

预期结果:

enter image description here

感谢您的帮助

4 个答案:

答案 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)

您可以使用SUBSTRINGCHARINDEX

来使用以下解决方案
SELECT SUBSTRING([Code], 1, CHARINDEX(' ', [Code] + ' ', CHARINDEX('BITWN', [Code]))) 
  

演示: http://sqlfiddle.com/#!18/004ac/1/0

答案 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