在某些表达式后提取某些字符串

时间:2019-04-04 07:33:33

标签: sql sql-server

我有一个表customer_info,其中的列PrintData包含许多信息。我想从该列获取交易ID。

列数据如下:

    <Line28>.TVR: 4000008000</Line28>
    <Line29>.IAD: 06020103649D00</Line29>
    <Line30>.TSI: E800</Line30>
    <Line31>.ARC: 00</Line31>
    <Line32>.CVM: PIN VERIFIED</Line32>
    <Line33>.TRAN ID: 000000000075169</Line33>

我只想获取000000000075169,即TRAN ID:

我已经尝试过:

SUBSTRING(PrintData,CHARINDEX('TRAN ID: ',PrintData),CHARINDEX('</Li',PrintData))

但是它没有给出写答案。

3 个答案:

答案 0 :(得分:1)

DECLARE @z NVARCHAR(MAX) = '
    <Line28>.TVR: 4000008000</Line28>
    <Line29>.IAD: 06020103649D00</Line29>
    <Line30>.TSI: E800</Line30>
    <Line31>.ARC: 00</Line31>
    <Line32>.CVM: PIN VERIFIED</Line32>
    <Line33>.TRAN ID: 000000000075169</Line33>
    '

    SELECT SUBSTRING(@z, CHARINDEX('TRAN ID: ', @z) + 9 -- offset charindex by 9 characters to omit the 'TRAN ID: '
                       , CHARINDEX('</Li', @z, CHARINDEX('TRAN ID: ', @z))-CHARINDEX('TRAN ID: ', @z) - 9) -- find the </Li AFTER the occurence of TRAN ID, and subract 9 to account for the offset

收益000000000075169。

答案 1 :(得分:1)

请问以下查询。

DECLARE @PrintData AS VARCHAR (200) = '<Line33>.TRAN ID: 000000000075169</Line33>';

SELECT SUBSTRING(@PrintData, 
                 CHARINDEX('TRAN ID: ', @PrintData) + LEN('TRAN ID: '), 
                 CHARINDEX('</Li',@PrintData) - (CHARINDEX('TRAN ID: ', @PrintData) + LEN('TRAN ID: '))
                 );

语法为SUBSTRING (expression, start_position, length)

更新:

根据MarcinJ的评论,对于</Line的多个实例,下面的查询将起作用。

DECLARE @PrintData VARCHAR(2000) = '
    <Line28>.TVR: 4000008000</Line28>
    <Line29>.IAD: 06020103649D00</Line29>
    <Line30>.TSI: E800</Line30>
    <Line31>.ARC: 00</Line31>
    <Line32>.CVM: PIN VERIFIED</Line32>
    <Line33>.TRAN ID: 000000000075169</Line33>
    ';

DECLARE @FindString AS VARCHAR (20) = 'TRAN ID: ';
DECLARE @LenFindString AS INT = LEN(@FindString);

SELECT SUBSTRING(@PrintData, 
                 CHARINDEX(@FindString, @PrintData) + @LenFindString, 
                 CHARINDEX('</Line', @PrintData, CHARINDEX(@FindString, @PrintData)) - (CHARINDEX(@FindString, @PrintData) + @LenFindString)
                 );

答案 2 :(得分:0)

我只会使用APPLY

select @PrintData AS Original_string, 
       substring(tran_id, 1, charindex('</', tran_id) -1) as Tran_ID
from ( values ( substring(PrintData, charindex('TRAN ID:', PrintData) + 8, len(PrintData)) )
     ) t(tran_id);