如何使用SSMS从字符串中提取特定文本?

时间:2018-10-26 08:48:44

标签: sql sql-server string ssms

我有一个字符串,其中包含有关ML和LTR的音量信息。如何从下面的字段中提取出来?

文字:

  

BRWN SPRTS 50 ML DRK RM AL N N SLR JRR

     

BRWN SPRTS DRK RM AL N N SLR JRR 700ML

     

700 ML DRK RM N NNG SNG-SM OTHR

     

SPRTS DRK RM AL 1.5 LTR N N TH-DPP-SHR

     

N N TH-KRKN TH-KRKN-BLCK-SPCD-RM 3.5 LTR

     

N N TH-KRKN 50 ML TH-KRKN-BLCK-SPCD-RM

我希望结果是这样的:

  

50ML

     

700ML

     

700ML

     

1.5LTR

     

3.5LTR

     

50ML

2 个答案:

答案 0 :(得分:0)

CREATE TABLE #TABLE1
    ([CLOUMNN] VARCHAR(40))
;

INSERT INTO #TABLE1
    ([CLOUMNN])
VALUES
    ('BRWN SPRTS 50 ML DRK RM AL N N SLR JRR'),
    ('BRWN SPRTS DRK RM AL N N SLR JRR 700ML'),
    ('700 ML DRK RM AL N N SNG-SM ALL OTHR'),
    ('SPRTS DRK RM AL 1.5 LTR N N TH-DPP-SHR'),
    ('N N TH-KRKN TH-KRKN-BLCK-SPCD-RM 3.5 LTR'),
    ('N N TH-KRKN 50 ML TH-KRKN-BLCK-SPCD-RM')
;
CREATE FUNCTION DBO.UDF_GETNUMERIC_1  
(@STRALPHANUMERIC VARCHAR(256))  
RETURNS VARCHAR(256)  
AS  
BEGIN  
DECLARE @INTALPHA INT  
SET @INTALPHA = PATINDEX('%[^0-9.]%', @STRALPHANUMERIC)  
BEGIN  
WHILE @INTALPHA > 0  
BEGIN  
SET @STRALPHANUMERIC = STUFF(@STRALPHANUMERIC, @INTALPHA, 1, '' )  
SET @INTALPHA = PATINDEX('%[^0-9.]%', @STRALPHANUMERIC )  
END  
END  
RETURN ISNULL(@STRALPHANUMERIC,0)  
END  

SELECT CONCAT([STRING],CASE WHEN [CLOUMNN]>0 THEN 'ML' ELSE 'LTR' END) 
FROM (SELECT DBO.UDF_GETNUMERIC_1([CLOUMNN])[STRING] ,CHARINDEX('ML',CLOUMNN)
 CLOUMNN FROM #TABLE1)A

输出

50ML
700ML
700ML
1.5LTR
3.5LTR
50ML

答案 1 :(得分:0)

这应该为您提供想要的结果,而无需进行任何循环...

IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL 
BEGIN DROP TABLE #TestData; END;

CREATE TABLE #TestData (
    CharacterString VARCHAR(100) NOT NULL 
    );
INSERT #TestData(CharacterString) VALUES
    ('BRWN SPRTS 50 ML DRK RM AL N N SLR JRR'),
    ('BRWN SPRTS DRK RM AL N N SLR JRR 700ML'),
    ('700 ML DRK RM AL N N SNG-SM ALL OTHR'),
    ('SPRTS DRK RM AL 1.5 LTR N N TH-DPP-SHR'),
    ('N N TH-KRKN TH-KRKN-BLCK-SPCD-RM 3.5 LTR'),
    ('N N TH-KRKN 50 ML TH-KRKN-BLCK-SPCD-RM');

--==================================================================

SELECT 
    *,
    Output = REPLACE(ISNULL(
        SUBSTRING(td.CharacterString, ns.num_ml, se.ml_end - ns.num_ml),
        SUBSTRING(td.CharacterString, ns.num_ltr, se.ltr_end - ns.num_ltr)
        ), ' ', '')
FROM
    #TestData td
    CROSS APPLY ( VALUES (
        NULLIF(PATINDEX('%[0-9]%ML%', td.CharacterString), 0),
        NULLIF(PATINDEX('%[0-9]%LTR%', td.CharacterString), 0)
        ) ) ns (num_ml, num_ltr)
    CROSS APPLY ( VALUES (
        CHARINDEX('ML', td.CharacterString, ns.num_ml) + 2,
        CHARINDEX('LTR', td.CharacterString, ns.num_ltr) + 3
        ) ) se (ml_end, ltr_end);

结果...

Output
------------
50ML
700ML
700ML
1.5LTR
3.5LTR
50ML