how to substring of a string in SQL

前端 未结 2 1711
遥遥无期
遥遥无期 2021-01-29 10:07

My data will be like that

IPDocument/XR/test_20120409_clearGAC.txt
IPDocument/XR/test_20120409_clearGAC_05.txt
IPDocument/XR/test_20120409_clearGAC_01.txt


        
相关标签:
2条回答
  • 2021-01-29 10:13
    SELECT SUBSTRING('IPDocument/XR/test_20120409_clearGAC.txt', CHARINDEX('09_','IPDocument/XR/test_20120409_clearGAC.txt')+3, 100)
    

    result : clearGAC.txt

    0 讨论(0)
  • 2021-01-29 10:24

    I assume that you want the _05 and _01 - the question is not clear.

    DECLARE @var VARCHAR(250)
    
    DECLARE @table TABLE ( val VARCHAR(250) )
    INSERT  INTO @table
            SELECT  'IPDocument/XR/test_20120409_clearGAC_01.txt'
            UNION ALL
            SELECT  'IPDocument/XR/test_20120409_clearGAC_05.txt'
            UNION ALL
            SELECT  'IPDocument/XR/test_20120409_clearGAC.txt' 
    
    
    SELECT  SUBSTRING(val, CHARINDEX('clearGAC', val), 50),
            SUBSTRING(SUBSTRING(val, CHARINDEX('_', val)+1, 50), CHARINDEX('_', SUBSTRING(val, CHARINDEX('_', val)+1, 50))+1, 50)
    FROM    @table
    

    Returns this:

    clearGAC_01.txt
    clearGAC_05.txt
    clearGAC.txt
    

    The third parameter in the CHARDINDEX can be larger than the length.

    EDIT: I added logic if you don't know if clearGAC is the name

    After reading your comment, you may just want this:

    I am going to pass ClearGAC.txt and see if it's in the DB. this ClearGAC.txt may be named like above codes.

    DECLARE @var VARCHAR(250)
    
    DECLARE @table TABLE ( val VARCHAR(250) )
    INSERT  INTO @table
            SELECT  'IPDocument/XR/test_20120409_clearGAC_01.txt'
            UNION ALL
            SELECT  'IPDocument/XR/test_20120409_clearGAC_05.txt'
            UNION ALL
            SELECT  'IPDocument/XR/test_20120409_clearGAC.txt' 
    
    
    SELECT  *
    FROM    @table
    WHERE   val LIKE '%clearGAC%.txt'
    
    0 讨论(0)
提交回复
热议问题