簡體   English   中英

提取字符串中兩個字符之間的字符串

[英]Extract string between two characters in a string

我有一組具有日期時間值的字符串,我想提取它們。 我不確定這是否可以使用 T-SQL。

CREATE TABLE #Temp (
BLOB_NM VARCHAR(100)
);

INSERT INTO #Temp
SELECT 'products_country_20200528102030.txt'
UNION ALL
SELECT 'products_territory_20190528102030.txt'
UNION ALL
SELECT 'products_country_2020-05-20_20200528102030.txt'
;

預期成績:

20200528102030
20190528102030
20200528102030

對於這個數據集,字符串函數應該這樣做:

select blob_nm, substring(blob_nm, len(blob_nm) - 17, 14) res from #temp

這個想法是從字符串的末尾倒數,並捕獲擴展名之前的 14 個字符(由字符串的最后 4 個字符表示)。

DB Fiddle 上的演示

blob_nm                                        | res           
:--------------------------------------------- | :-------------
products_country_20200528102030.txt            | 20200528102030
products_territory_20190528102030.txt          | 20190528102030
products_country_2020-05-20_20200528102030.txt | 20200528102030

如果對幫助器 function 感興趣...我創建了這個 TVF 因為我分層提取字符串的部分(左、右、charindex、reverse、substing 等)

例子

Select * 
 From  #Temp A
 Cross Apply [dbo].[tvf-Str-Extract](Blob_NM,'_','.') B

退貨

BLOB_NM                                         RetSeq  RetVal
products_country_20200528102030.txt             1       20200528102030
products_territory_20190528102030.txt           1       20190528102030
products_country_2020-05-20_20200528102030.txt  1       20200528102030

Function 如果有興趣

CREATE FUNCTION [dbo].[tvf-Str-Extract] (@String varchar(max),@Delim1 varchar(100),@Delim2 varchar(100))
Returns Table 
As
Return (  

    Select RetSeq = row_number() over (order by RetSeq)
          ,RetVal = left(RetVal,charindex(@Delim2,RetVal)-1)
    From  (
            Select RetSeq = row_number() over (order by 1/0)
                  ,RetVal = ltrim(rtrim(B.i.value('(./text())[1]', 'varchar(max)')))
            From  ( values (convert(xml,'<x>' + replace((Select replace(@String,@Delim1,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>').query('.'))) as A(XMLData)
            Cross Apply XMLData.nodes('x') AS B(i)
          ) C1
    Where charindex(@Delim2,RetVal)>1

)

我想:

  • 文件擴展名並不總是 3 個字符長度
  • 您的日期/時間格式始終為 14 個字符

嘗試這個:

select 
CONVERT(DATETIME, STUFF(STUFF(STUFF(left(right(BLOB_NM, charindex('_', reverse(BLOB_NM) + '_') - 1), 14),13,0,':'),11,0,':'),9,0,' ')) as Result
from #Temp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM